在使用Stream流将List通过Collectors.groupingBy方法转换成Map,原本List中的顺序全被打乱

发布时间 2023-08-08 17:27:07作者: Sherlock先生

问题:在使用Stream流将List通过Collectors.groupingBy方法转换成Map,发现原本List中的顺序全被打乱了。

 Map<Map<String, String>, List<DealDataResponse>> groups = dealDataResponses.stream().collect(
                    Collectors.groupingBy(x ->
                            groupmap(DateHelper.reserveToDay(x.getDealTime()), x.getEstateCode())
                    )
            );
 Map<Map<String, String>, List<DealDataResponse>> groups = dealDataResponses.stream().collect(
                    Collectors.groupingBy(x ->
                            groupmap(DateHelper.reserveToDay(x.getDealTime()), x.getEstateCode()),LinkedHashMap::new,Collectors.toList()
                    )
            );

瞅瞅这两块代码的区别。

从第一块代码groupby后顺序会被打乱变成无序,因为看源码他默认实现是Collectors.groupingBy(Function<? super T, ? extends K> classifier, HashMap::new, Collectors.toList()) ,中间的参数 HashMap::new 指定返回的是HashMap类型,而HashMap集合底层是哈希表,所以是无序集合,也就是存取顺序不同。

从第二块代码方法也提供了有序的实现类LinkedHashMap,也就是链表+哈希表的结构来实现有序。所以在之后使用groupingBy方法来实现List和Map的转换时,可以直接使用:Collectors.groupingBy(Function<? super T, ? extends K> classifier, LinkedHashMap::new, Collectors.toList()) 方法。就不会出现list顺序被打乱的情况。