javasortingobjectjava-streammaps

Sorting a Map<Object, List<Object>> by Object Parameter in Java


Can you please help me sort a map like this

Map<Object, List<Object>> halls = new HashMap()<>;

where the key Object has one of his parameters to be numberOfSeats and the whole map should be sorted by the most number of seats in reverse order. I tried doing it with streamAPI but i can't seem to make it work.

Something like:

 halls.entrySet().stream().sorted((h1, h2) -> h1.getSeatsNumber.compareTo(h2.getSeatsNumber));

Solution

  • Instead of using HashMap, create a TreeMap which is sorted by key and provide a custom comparator:

    Map<MyObject, List<MyObject>> halls = new TreeMap<>(
            Comparator.comparingInt(MyObject::getSeatsNumber).reversed()
    );
    

    If you have a collection of MyObject that needs to be collected into map, this can be done using Collectors.groupingBy with a supplier of the TreeMap:

    List<MyObject> list = new ArrayList<>(); // input list of MyObject
    
    Map<MyObject, List<MyObject>> halls2 = list
            .stream()
            .collect(Collectors.groupingBy(
                x -> x,
                () -> new TreeMap<>(
                    Comparator.comparingInt(MyObject::getSeatsNumber).reversed()
                ),
                Collectors.toList()
            ));