Why parallel stream get collected sequentially in Java 8

前端 未结 2 948
醉梦人生
醉梦人生 2020-11-29 04:57

Why forEach prints numbers in random order, while collect always collects elements in original order, even from parallel stream?

In         


        
2条回答
  •  粉色の甜心
    2020-11-29 05:40

    The Collectors.toList method specifies that the returned Collector adds elements to the list in encounter order.

    Returns:

    a Collector which collects all the input elements into a List, in encounter order

    It doesn't matter whether the Stream is parallel; the order is preserved.

    Additionally, looking at the Collectors source code, the returned Collector calls addAll on an ArrayList when merging, and that preserves the order. E.g. if one thread has {1, 2} and the next thread has {3, 4}, then the call to addAll yields {1, 2, 3, 4}. Also, the returned Collector doesn't have the UNORDERED characteristic.

提交回复
热议问题