本文介绍了Java流映射和收集 - 生成的容器的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

List<MyObject> myList = new ArrayList<>(); 
//populate myList here

List<String> nameList = myList.stream()
        .map(MyObject::getName)
        .collect(Collectors.toList());

在上面的代码中,我可以期待 MyObject nameList 中的$ c>名称始终与 myList 的顺序相同?

In above code, can I expect that order of MyObject names in nameList is always the same as the order of myList?

推荐答案

是的,即使您使用并行流,只要您没有将其显式转换为模式。

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:


  • 如果您通过 unordered() call

  • 如果流源报告它是无序的(例如, HashSet 流是无序的,因为顺序是依赖于实现的,你不能依赖它。)

  • 如果你使用无序终端操作(例如, forEach()操作或收集到无序收集器喜欢 toSet()

  • 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.

这篇关于Java流映射和收集 - 生成的容器的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 06:35