So I came across this method which is able to sort HashMaps by value.
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
return map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new
));
}
I want to use the reversed() method on the Comparator but I can't seem to find the right place to put it.
The reversed() method should be called on the Comparator returned by comparingByValue(). Java's type inference breaks down here, unfortunately, so you'll have to specify the generic types:
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue
(Map<K, V> map) {
return map.entrySet()
.stream()
.sorted(Map.Entry.<K, V> comparingByValue().reversed())
// Type here -----^ reversed() here -------^
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new
));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With