简体   繁体   English

Java Streams - 如何在使用 Collector groupingBy() 时保留元素的初始顺序

[英]Java Streams - How to preserve the initial Order of elements while using Collector groupingBy()

I'm trying to convert a list of objects into a list of lists of objects, ie List<T> into List<List<T>> and group them by a list of strings used as sorting keys .我正在尝试将对象列表转换为对象列表列表,即将List<T>转换为List<List<T>>并通过用作排序的字符串列表对它们进行分组。

The problem is that after the groupingBy() , the return value is a map, and that map a different order of values.问题是在groupingBy()之后,返回值是一个映射,并且映射不同的值顺序。

What can I do to preserve the initial order of elements in the list groupedTreesList ?我可以做些什么来保留列表groupedTreesList中元素的初始顺序?

My code:我的代码:

Map<List<String>,List<QueryTreeProxy>> groupedMap = treesProxyList.stream()
    .collect(Collectors.groupingBy(
        QueryTreeProxy::getMappingKeys,
        Collectors.toList()
    ));

List<List<QueryTreeProxy>> groupedTreesList = groupedMap.values().stream().toList();

groupingBy() , the return value is a map and that map output a different order of values list groupingBy() ,返回值是一个映射,该映射输出不同顺序的值列表

You can use another flavor of groupingBy(classifier, mapFactory, downstream) , which allows you to specify the type of the Map.您可以使用另一种groupingBy(classifier, mapFactory, downstream) ,它允许您指定 Map 的类型。 And we can use LinkedHashMap to preserve the initial order.我们可以使用LinkedHashMap来保存初始顺序。

And there's no need to generate the second stream, you can use parameterized contractor of ArrayList instead.并且不需要生成第二个流,您可以使用ArrayList的参数化承包商来代替。

Map<List<String>, List<QueryTreeProxy>> groupedMap = treesProxyList.stream()
    .collect(Collectors.groupingBy(
        QueryTreeProxy::getMappingKeys,
        LinkedHashMap::new,
        Collectors.toList()
    ));
    
List<List<QueryTreeProxy>> groupedTreesList = new ArrayList<>(groupedMap.values());

Besides that, using a mutable object as a key isn't a good practice.除此之外,使用可变对象作为键并不是一个好习惯。

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

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