如何将此代码片段变形为 Java 8,其中逻辑取决于索引值?

How to morph this code snippet into Java 8 where logic depends on index value?

我有这段代码,我希望在 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) 部分。

您可以使用 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());

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

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