简体   繁体   English

Java groupingBy收集器是否保留列表顺序?

[英]Does Java groupingBy collector preserve list order?

Consider a list List<People> where the elements are sorted in ascending order of People.getAge() . 考虑一个列表List<People> ,其中元素以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? 如果我们使用Collectors.groupingBy(People::getCity)对列表进行分组,那么每个组/城市的结果列表是否会按年龄排序?

In practice, it does seem to preserve the order. 实际上,它似乎可以保留顺序。 I'm looking for a guarantee. 我在寻找保证。

The Javadoc for the method says: 该方法的Javadoc说:

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 如果不需要保留元素在结果Map收集器中出现的顺序,则使用groupingByConcurrent(Function)可能会提供更好的并行性能

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; 它讨论它们是否按顺序到达,这意味着它们是否按顺序传递给键提取器Function和任何下游收集器。 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. 实际上, groupingBy的当前实现使用不保留键顺序的HashMap

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. 如果Stream仍然是有序的,并且您分组到一个保留顺序的下游收集器,则它将保留该顺序,而Concurrent版本则不会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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