Is .collect guaranteed to be ordered on parallel streams?

前端 未结 2 657
深忆病人
深忆病人 2020-12-07 16:41

Given I have a list of Strings List toProcess. The results have to be in the order the original lines were given. I want to utilize the new parall

2条回答
  •  旧巷少年郎
    2020-12-07 16:59

    You are guaranteed to get the elements in encounter order.

    From documentation of toList:

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

    See java.util.streams summary for more information on the term "encounter order".

    Furthermore, List#spliterator documentation requires that the all implementations of List produce spliterators that are ORDERED:

    The Spliterator reports Spliterator.SIZED and Spliterator.ORDERED. Implementations should document the reporting of additional characteristic values.

    Oddly enough, while List interface requires iterator() to produce elements in "proper sequence", spliterator() is only required to be ordered but not specifically required to follow the list's natural ordering.

    So, to answer your question, the list produced by toList is guaranteed to contain the elements exactly as the source list's spliterator orders them. It does not matter whether the stream is parallel or sequential.

提交回复
热议问题