我可以将此表达式转换为Java 8中的流API表达式

时间:2017-01-13 16:45:06

标签: lambda java-8 java-stream

以下是代码段:

List<Double> dataLeft, List<Double> dataRight;
double sumLeft = 0, sumRight = 0;
for (int i = 0; i < dataLeft.size(); i++) {
  sumLeft += dataLeft.get(i)*(dataLeft.size() - i);
  sumRight += dataRight.get(i)*(dataRight.size() - i);
}

dataLeft和dataRight的大小相同。

2 个答案:

答案 0 :(得分:3)

当然,但你获得的收益不大。你甚至会失去可读性,恕我直言

sumLeft += IntStream.range(0, dataLeft.size()).mapToDouble(i-> dataLeft.get(i) * (dataLeft.size() - i)).sum();
sumRight += IntStream.range(0, dataLeft.size()).mapToDouble(i-> dataRight.get(i) * (dataRight.size() - i)).sum();

答案 1 :(得分:0)

这个怎么样:

private double sum(final List<Double> data) {
    final AtomicInteger index = new AtomicInteger(0);
    final int n = data.size();
    return data.stream().mapToDouble(d -> d * (n - index.getAndIncrement())).sum();
}

然后像这样使用它:

sumLeft += sum(dataLeft);
sumRight += sum(dataRight);