在
Aggregating with Streams中,Brian Goetz比较使用()填充集合并使用()执行相同操作,使用以下两个片段:
Set uniqueStrings = ()
.collect(HashSet::new,
HashSet::add,
HashSet::addAll);
和,
Set set = new HashSet<>();
().forEach(s -> (s));
然后他解释说:
The key
difference is that, with the forEach() version, multiple threads are trying to access a single result
container simultaneously, whereas with parallel collect(), each thread has its own local result
container, the results of which are merged afterward.
据我所知,只有当流是并行的时,多个线程才会在forEach()情况下工作.但是,在给出的示例中,forEach()在顺序流上运行(不调用parallelStream()).
那么,forEach()总是并行工作,或者代码片段应该调用parallelStream()而不是stream(). (或者我错过了什么?)