Java groupingBy collector是否保留列表顺序? [英] Does Java groupingBy collector preserve list order?

查看:161
本文介绍了Java groupingBy collector是否保留列表顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个列表列表< People> 其中元素按的升序排序> People.getAge() 。如果我们使用 Collectors.groupingBy(People :: getCity)对此列表进行分组,那么每个组/城市的结果列表是否会按年龄排序?

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.

该方法的Javadoc说:

The Javadoc for the method says:


如果保留订单不需要在生成的Map收集器中出现哪些元素,使用groupingByConcurrent(Function)可以提供更好的并行性能

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.

推荐答案

理解合同的关键在于元素出现的顺序 。它讨论了它们是否按顺序到达,这意味着它们是否按顺序传递给密钥提取器 Function 和任何下游收集器;它没有说明订单是否会保留在任何由此产生的积累中;事实上, groupingBy 的当前实现使用 HashMap ,但不保留密钥顺序。

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.

您询问它是否引用了列表中的项目顺序。如果您指的是创建Stream的List,则在List上创建的Stream会开始排序,但是某些流操作会更改顺序或使其无序,因此它引用的顺序是指管道之后生成的顺序如果流保持有序,则完成操作。如果流操作使流无序,则元素在收集器中出现的顺序不再是问题。

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.

如果您指的是项中的项目顺序列出分组的项目是收集到的,是的,它确实如此,因为元素出现的顺序是元素的处理顺序。分组到下游收集器时也是如此;如果仍然订购了Stream,并且您将组合到保留订单的下游收集器,则这将保留该订单,而Concurrent版本可能不会。

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.

这篇关于Java groupingBy collector是否保留列表顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆