我有以下方法
private Set<Chapter> chapters;
public long getCount() {
long count = 0;
for (Chapter chapter : chapters) count += chapter.getCount();
return count;
}
我想使用 Java 8 特性(如流和 lambda)改进这段代码,但我无法将外部变量更改为 lambda,所以我试图作弊,但这是一个糟糕的解决方案。
public long getCount() {
final long[] count = {0};
chapters.parallelStream().forEach(chapter -> count[0] += chapter.getCount());
return count[0];
}
你能帮我解决这个问题吗?或者提供一些有用的链接给我。 对不起,如果它是重复的。
最佳答案
没关系了,我已经找到了 mapToLong()
https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html
public long getCount() {
return chapters.parallelStream().mapToLong(Chapter::getCount).sum();
}
关于java - 如何使用并行流将 foreach 更改为 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37249182/