如何将此代码片段转换为Java 8,其中逻辑依赖于索引值?

时间:2015-03-11 12:01:14

标签: 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);

对我来说,很容易将代码转换为Java 8流,但我不知道如何实现data.get(i * step)部分。

2 个答案:

答案 0 :(得分:5)

您可以使用IntStream,它是“一系列支持顺序和并行聚合操作的原始int值元素”。

例如:

IntStream.range(0, 20)
         .forEach(i -> {
              Instance inst = data.get(i * step).getInstance();
              outcome.add(inst.isPresent() ? 100d : 0d);
          });

作为@AlexisC。建议,这可以简化为单行:

List<Double> outcome = 
         IntStream.range(0, 20)
                  .mapToObj(i -> data.get(i*step).getInstance().isPresent()? 100d : 0d)
                  .collect(toList());

答案 1 :(得分:2)

这是一个替代解决方案,它不会改变列表但使用收集器(通常建议在使用流时使用无副作用的代码,特别是如果您将来可以并行化它们):

List<Double> outcome = IntStream.range(0, 20)
                        .mapToObj(i -> data.get(i * step).getInstance())
                        .map(inst -> inst.isPresent() ? 100d : 0d)
                        .collect(toList());
相关问题