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
));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…