To sort it int ascending order I can use:
myMap.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
How can I do it in decreasing order?
LinkedHashMap just maintains insertion order. If you want to sort based on value, you may need to write your own comparator .
To sort in reverse order, pass Comparator.reverseOrder()
as parameter to comparingByValue
.
To get a LinkedHashMap
, you must specifically request one with the 4-argument toMap()
. If you don't specify what kind of a map you want, you will get whatever the default is, which currently happens to be a HashMap
. Since HashMap
doesn't preserve the order of elements, it will definitely not do for you.
myMap.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(x,y)-> {throw new AssertionError();},
LinkedHashMap::new
));
With static imports, it becomes a bit more pleasant:
myMap.entrySet().stream()
.sorted(comparingByValue(reverseOrder()))
.collect(toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(x,y)-> {throw new AssertionError();},
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