Java Collectors.groupingBy()---List 是有序的吗?

2022-01-22 00:00:00 java-8 java java-stream collectors

对于返回 Map<K,List<T>>Collectors.groupingBy() 是否暗示 List<T>code> 是为了评估流吗?

For the Collectors.groupingBy() that returns Map<K,List<T>> is it implied that the List<T> is in order that the stream is evaluated?

我没有看到列表排序的明确描述,而并发版本明确声明没有排序.如果它不是以某种方式订购的,我希望它是一个集合,我看不出它可能是什么其他订购,除了收到的订单.

I see no explicit description of the ordering of the list, whereas the concurrent version explicitly states no ordering. If it weren't ordered somehow, I'd expect it to be a Collection though, and I don't see what other ordering it could possibly be, other than order received.

我希望可以保证每个列表中的最后一个值是该组收到的最后一个值.

I'm hoping it's guaranteed that the last value in each list is the last value received for that group.

推荐答案

groupingBy() 说:

实施要求:

这会产生类似的结果:

groupingBy(classifier, toList());

<代码>toList() 说:

返回:

一个Collector,它将所有输入元素按遇到顺序收集到一个List

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

所以,要回答您的问题,只要您的流具有定义的 遇到订单,保证得到有序列表.

So, to answer your question, as long as your stream has a defined encounter order, you're guaranteed to get ordered lists.

正如@Holger 指出的那样,groupingBy() 还必须尊重遇到顺序以保留 toList() 的排序约束.本说明强烈暗示了它确实如此的事实:

As @Holger points out, groupingBy() would also have to respect encounter order to preserve toList()'s ordering constraint. The fact that it does is strongly implied in this note:

实施说明:

...如果不需要保留元素呈现给下游收集器的顺序,则使用 groupingByConcurrent(Function, Collector) 可能会提供更好的并行性能.

...If preservation of the order in which elements are presented to the downstream collector is not required, using groupingByConcurrent(Function, Collector) may offer better parallel performance.

相关文章