Chi*_*ron 1 java collections java-8
我有这个代码,我想在Java 8风格中看到它:
List<Double> outcome = ....
int step = data.size / 20;
for (int i = 0; i < 20; i++) {
Instance inst = data.get(i * step).getInstance();
if (inst.isPresent())
outcome.add(100);
else
outcome.add(0.0);
Run Code Online (Sandbox Code Playgroud)
对我来说,很容易将代码转换为Java 8流,但我不知道如何实现该data.get(i * step)部分.
您可以使用IntStream,这是" 一系列支持顺序和并行聚合操作的原始int值元素 ".
例如:
IntStream.range(0, 20)
.forEach(i -> {
Instance inst = data.get(i * step).getInstance();
outcome.add(inst.isPresent() ? 100d : 0d);
});
Run Code Online (Sandbox Code Playgroud)
作为@AlexisC.建议,这可以简化为单行:
List<Double> outcome =
IntStream.range(0, 20)
.mapToObj(i -> data.get(i*step).getInstance().isPresent()? 100d : 0d)
.collect(toList());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
91 次 |
| 最近记录: |