Does Java groupingBy collector preserve list order?

自闭症网瘾萝莉.ら 提交于 2019-12-08 16:55:24

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/37251477/does-java-groupingby-collector-preserve-list-order

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