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();
>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.