Java 如何使用并行流将foreach更改为lambda

Java 如何使用并行流将foreach更改为lambda,java,java-8,java-stream,Java,Java 8,Java Stream,我有以下方法 private Set<Chapter> chapters; public long getCount() { long count = 0; for (Chapter chapter : chapters) count += chapter.getCount(); return count; } 你能帮我吗?或者提供一些有用的链接给我。 如果是重复的,很抱歉。不再重要,我已经找到了使用mapToLong()的单行解决方案。 请注意,如果没有

我有以下方法

private Set<Chapter> chapters;
public long getCount() {
    long count = 0;
    for (Chapter chapter : chapters) count += chapter.getCount();
    return count;
}
你能帮我吗?或者提供一些有用的链接给我。
如果是重复的,很抱歉。

不再重要,我已经找到了使用
mapToLong()的单行解决方案。


请注意,如果没有大量的章节,使用
parallelStream
可能会严重影响性能。这不是一个“糟糕的解决方案”,因为对数组元素的并发访问完全被破坏了。所以这根本不是解决办法。但是你已经…
public long getCount() {
    final long[] count = {0};
    chapters.parallelStream().forEach(chapter -> count[0] += chapter.getCount());
    return count[0];
}
public long getCount() {
    return chapters.parallelStream().mapToLong(Chapter::getCount).sum();
}