简体   繁体   中英

Does Java groupingBy collector preserve list order?

Consider a list List<People> where the elements are sorted in ascending order of People.getAge() . If we group this list using Collectors.groupingBy(People::getCity) , would the resultant lists for each of the groups/cities remain sorted on age?

In practice, it does seem to preserve the order. I'm looking for a guarantee.

The Javadoc for the method says:

If preservation of the order in which elements appear in the resulting Map collector is not required, using groupingByConcurrent(Function) may offer better parallel performance

I'm not sure if this refers to the order of items on list.

The key to understanding the contract is where it says "the order in which elements appear ". It talks about whether they arrive in order, which implies whether they are passed in to the key extractor Function and to any downstream collector in order; it doesn't say anything about whether the order will be preserved in any resulting accumulation; in fact the current implementation of groupingBy uses a HashMap which does not preserve the key order.

You ask if it refers to the order of items on the list. If you are referring to the List that the Stream was created from, a Stream created on a List does start out ordered, but some stream operations change the order or make it unordered, so the ordering it refers to refers to the resulting order after pipeline operations are done IF the stream remains ordered. If stream operations make the stream unordered, the order in which elements appears at the collector is not an issue any longer.

If you are referring to the order of items in the List the grouped items are collected to, yes, it does, because the "order in which the elements appear" is the order in which the elements are processed. The same holds true when grouping to a downstream collector; if the Stream is still ordered, and you group to a downstream collector that preserves order, this will preserve that order, while the Concurrent version may not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM