我不知道为什么应该使用聚合函数。 我的意思是,如果可以提高性能,聚合函数应该可以并行执行。
https://docs.oracle.com/javase/tutorial/collections/streams/parallelism.html
但事实并非如此,根据文档,如果不使用parallelStream()而不是stream(),代码将不会是并行的,所以 如果没有更好的结果,为什么我应该使用stream()?
这些代码不应该是相同的吗?
//it is not parallel
listOfIntegers.stream()
.forEach( e -> System.out.print(e+" "));
还有
//it is parallel
listOfIntegers.parallelStream()
.forEach( e -> System.out.print(e+" "));
最佳答案
如果您使用stream
,列表中的所有数据将按顺序处理,而如果您使用parallelStream
,您的数据可能不会按顺序处理。
考虑方法
static void test(Integer i){
try {
Thread.sleep((long) (1000*Math.random()));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(i);
}
并使用 parallelStream
和 stream
比较此方法的输出
关于java - Java 流中的聚合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37030729/