'Sort List<Map.Entry<String, Integer>> in primary and secondary way?
Okay. So I have an ArrayList of Map<String, Integer>:
Set<Map.Entry<String, Integer>> wordSet = map.entrySet();
List<Map.Entry<String, Integer>> wordList = new ArrayList<>(wordSet);
wordList.sort((w1, w2) -> w2.getValue().compareTo(w1.getValue()));
As you can see here this sort will only sort based on the Value in the Map<K,V>. I wanna modify the lambda-expression so it PRIMARILY checks for the greatest value, and SECONDARY checks the alphabetical order. However, I'm not sure how to create a lambda-expression in this way that has a Primary and Secondary way.
Solution 1:[1]
Use the Comparator utility methods instead. Replace your current with:
wordList.sort(Comparator.comparing(Map.Entry::getValue))
This utility method makes a comparator that does what your comparator does: map both entries by calling getValue, then compare that object.
All comparators have a .thenComparing method:
Comparator<Map.Entry<String, Integer>> secondOrder = Comparator.comparing(e -> e.getKey());
wordList.sort(Comparator.comparing(Map.Entry::getValue).thenComparing(secondOrder));
This will compare on value, and if those are equal, then compare on key. You can make that compare on whatever you please.
Solution 2:[2]
It seems that you need to sort the map entries by value () in descending order and then by keys (words) in alphabetical order.
Map.Entry has its own static comparator methods Map.Entry::comparingByValue and Map.Entry::comparingByKey which can be joined using Comparator::thenComparing:
wordList.sort(Map.Entry.<String, Integer>comparingByValue(Comparator.reverseOrder())
.thenComparing(Map.Entry.comparingByKey()));
Also, Comparator::reversed may be used instead of Comparator::reverseOrder:
wordList.sort(Map.Entry.<String, Integer>comparingByValue()
.reversed()
.thenComparing(Map.Entry.comparingByKey())
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rzwitserloot |
| Solution 2 |
