在使用集合时,在forEach调用之前是否有特定插入流/并行流的原因?
示例:
Collection<Object> foo;
foo.forEach(); // Goes through every item in foo
foo.stream().forEach(); // Does stream make a difference here
foo.parallelStream().forEach(); // Does this make a difference here?
谢谢
parallelStream()
或者parallel()
,那么forEach
方法就会以并行的方式执行。然而,你必须确保传入Consumer
函数不会修改任何数据或者是线程安全的。 - Peter LawreyforEach
与在集合上使用不同,它不能保证维护元素顺序,并且在并行流的情况下,将在没有任何同步的情况下调用操作。forEachOrdered
更像是Collection.forEach
,但在没有任何其他流操作的情况下没有意义。 - Holger