以下是代码段:
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的大小相同。
答案 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);