Home > Back-end >  How to sort the hashmap in descending order by values and if the values are the same then by key in
How to sort the hashmap in descending order by values and if the values are the same then by key in

Time:09-17

I have a HashMap<Integer, Integer> named "relevance" e.g {2: 3, 1: 3, 3: 3, 5: 4, 4: 4, 6: 3} and I want do DESC sorting by values.

Map<Integer, Integer> sortedRelevance = new LinkedHashMap<>();
relevance.entrySet()
        .stream()
        .sorted(Map.Entry.<Integer, Integer>comparingByValue(Comparator.reverseOrder()))
        .forEachOrdered(x -> sortedRelevance.put(x.getKey(), x.getValue()));

I get a hashmap {5: 4, 4: 4, 2: 3, 1: 3, 3: 3, 6: 3}. How can I sort ascending keys with the same values?

CodePudding user response:

You can "chain" Comparators by adding calls to thenComparing:

Map<Integer, Integer> sortedRelevance = new LinkedHashMap<>();
relevance.entrySet()
         .stream()
         .sorted(Map.Entry.<Integer, Integer> comparingByValue(Comparator.reverseOrder())
                          .thenComparing(Map.Entry.comparingByKey()))
         .forEachOrdered(x -> sortedRelevance.put(x.getKey(), x.getValue()));
  • Related