Java stream map and collect - order of resulting container

◇◆丶佛笑我妖孽 提交于 2019-12-03 06:28:59

问题


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?


回答1:


Yes, you can expect this even if you are using parallel stream as long as you did not explicitly convert it into unordered() mode.

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 like toSet())

In your case none of these conditions met, thus your stream is ordered.



来源:https://stackoverflow.com/questions/30258566/java-stream-map-and-collect-order-of-resulting-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!