Search code examples
javaandroidhashmap

Sorting the Map in descending order based on the value and sort the key in ascending order if value is duplicate


I am using map interface to read from a file and then store the values in that as a key value pair.

Map<String, Integer> map = new HashMap<>();

The value is

A 25
D 10
B 15
E 15
C 17

I want to first sort by value in descending order Sorting the Map<Key,Value> in descending order based on the value . This will help to achieve the order in descending order. But if the value are duplicate i want to sort by key in ascending order.

Expected Output

A 25
C 17
B 15
E 15
D 10

Does any one know how to achieve this .


Solution

  • You can use Comparator.comparing and thenComparing to sort in the correct order. Streams can be used to sort and collect the new Map to a LinkedHashMap to retain the new order.

    Map<String, Integer> map = Map.of("A", 25, "D", 10, "B", 15, "E", 15, "C", 17);
    Map<String, Integer> result = map.entrySet().stream()
        .sorted(Comparator.<Map.Entry<String, Integer>>comparingInt(Map.Entry::getValue)
           .reversed().thenComparing(Map.Entry::getKey))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, 
             (a,b)->b, LinkedHashMap::new));
    System.out.println(result);
    

    Demo