Search code examples
javalistjava-streamgroupingcollectors

Java groupingBy is always changing order


i have List with simple object:

private String unit;
private Double value;

List looks like that:

f, 1.0;
ml, 15.0;
g, 9.0

I have created a simple function where I want to group this values and put them to the map with unit as a key, and list of objects as value, but I want to save the order like in my original list. This is my current solution:

myList.stream()
    .collect(groupingBy(MyObject::getUnit));

But after that my map is sorted alphabetically this way: f, g, ml instead of f, ml, g. Is there any alternative for groupingBy to fix it?


Solution

  • The issue is that groupingBy puts things into some map, probably a HashMap, which has no guaranteed ordering.

    Use the groupingBy overload which takes a Supplier<M> mapFactory, to get a map with an ordering guarantee, e.g.

    myList.stream()
        .collect(groupingBy(MyObject::getUnit,
                            LinkedHashMap::new,
                            Collectors.toList()));