Java 流映射和收集 - 结果容器的顺序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30258566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java stream map and collect - order of resulting container
提问by Lahiru Chandima
List<MyObject> myList = new ArrayList<>();
//populate myList here
List<String> nameList = myList.stream()
.map(MyObject::getName)
.collect(Collectors.toList());
In above code, can I expect that order of MyObject
names in nameList
is always the same as the order of myList
?
在上面的代码中,我可以期望MyObject
名称nameList
的顺序始终与 的顺序相同myList
吗?
回答by Tagir Valeev
Yes, you can expect this even if you are using parallel stream as long as you did not explicitly convert it into unordered()
mode.
是的,即使您使用的是并行流,只要您没有将其显式转换为unordered()
模式,您也可以预料到这一点。
The ordering never changes in sequential mode, but may change in parallel mode. The stream becomes unordered either:
顺序在顺序模式下永远不会改变,但在并行模式下可能会改变。流变得无序:
- If you explicitly turn it into unordered mode via
unordered()
call - If the stream source reports that it's unordered (for example,
HashSet
stream is unordered as order is implementation dependent and you cannot rely on it) - If you are using unordered terminal operation (for example,
forEach()
operation or collecting to unordered collector liketoSet()
)
- 如果您通过
unordered()
调用将其显式转换为无序模式 - 如果流源报告它是无序的(例如,
HashSet
流是无序的,因为顺序是依赖于实现的,你不能依赖它) - 如果您正在使用无序终端操作(例如,
forEach()
操作或收集到无序收集器之类的toSet()
)
In your case none of these conditions met, thus your stream is ordered.
在您的情况下,这些条件都不满足,因此您的流已被订购。