在 java 8 中,当我这样做时,
类型 1
list.stream().parallel().map(/**/).unordered().filter(/**/).collect(/**/);
类型 2
list.stream().parallel().unordered().map(/**/).filter(/**/).collect(/**/);
由于两个流都是并行的,我可以理解每个操作(如过滤器、映射等)的所有对象将并行执行,但操作本身将按照定义的顺序顺序执行。
问题
1.在 Type1 中,我确实在 map() 操作之后说了 unordered() 。那么,map() 操作是否尝试处理“排序”,因为它在 unOrdered() 之前?
2.在Type2中,Ordering is not maintained across map, filter ops right?我的理解正确吗?
最佳答案
Stream
状态修改方法有 3 种:
-
Returns an equivalent stream that is sequential. May return itself, either because the stream was already sequential, or because the underlying stream state was modified to be sequential.
-
Returns an equivalent stream that is parallel. May return itself, either because the stream was already parallel, or because the underlying stream state was modified to be parallel.
-
Returns an equivalent stream that is unordered. May return itself, either because the stream was already unordered, or because the underlying stream state was modified to be unordered.
如您所见,这三个都可能修改底层流状态,这意味着方法在流链中的位置无关紧要。
您的两个示例相同。那么这些将是:
list.stream().parallel().map(/**/).filter(/**/).unordered().collect(/**/);
list.stream().map(/**/).filter(/**/).unordered().parallel().collect(/**/);
list.stream().unordered().map(/**/).parallel().filter(/**/).collect(/**/);
list.stream().unordered().parallel().map(/**/).filter(/**/).collect(/**/);
您应该点击 unordered链接并阅读 javadoc 以了解有关流的排序的更多信息。
关于Java Unordered() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56516407/