分组后流不保留顺序 [英] Stream doesn't preserve the order after grouping

查看:96
本文介绍了分组后流不保留顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表名称 availableSeats 我正在按 blockIndex 属性进行排序和分组,如下所示:

I have a List name availableSeats I am sorting and grouping by the blockIndex property like below:

availableSeats.stream()
                .sorted(Comparator.comparing(SeatedTicketAssignment::getBlockIndex))
                .collect(Collectors.groupingBy(SeatedTicketAssignment::getBlockIndex))
                .forEach((block, blockAssignments) -> {
                     //Rest of the code
                } 

问题是分组的结果没有按blockIndex排序。

The problem is that the result of grouping by is not sorted by the blockIndex.

推荐答案

保持记住,收集器#groupingBy(功能)将返回 HashMap ,这不保证订单。如果你想要按顺序排列聚合标识(您的 i%2 == 0 结果)显示,然后您可以使用 LinkedHashMap

Keep in mind, Collectors#groupingBy(Function) will return a HashMap, which does not guarantee order. If you want the ordering to be in the order that the aggregate identity (your i % 2 == 0 result) shows up, then you can use LinkedHashMap:

.collect(Collectors.groupingBy(i -> i % 2 == 0, LinkedHashMap::new, Collectors.toList()))

会返回a LinkedHashMap< Boolean,List< SeatedTicketAssignment>> (因为您的收集器按布尔值分组)。此外,由于收集器使用的列表是 ArrayList ,因此它应该保留流相对于列表的迭代顺序。

Would return a LinkedHashMap<Boolean, List<SeatedTicketAssignment>> (since your collector is grouped by a boolean). Additionally, since the list utilized by the collector is an ArrayList, it should preserve the iteration order of the stream relative to the list.

这篇关于分组后流不保留顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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