Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

java stream group by to ordered map

im trying to convert a list of object to a list of list of objects – List to List<List> and group them by a list of strings used as sorting keys.
the problem is that after the groupby, the return value is a map and that map output a different order of values list.

what can i do to get persistent order of groupedTreesList values list?

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

groupingBy(), the return value is a map and that map output a different order of values list

You can use another flavor of groupingBy(classifier, mapFactory, downstream), which allows you to specify the type of the Map. And we can use LinkedHashMap to preserve the initial order.

And there’s no need to generate the second stream, you can use parameterized contractor of ArrayList instead.

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading