This question has already been answered:

Help, you need to sort the Map in reverse order of value (Value).

Map<String, Integer> map = new HashMap<>(); map.put("Text1", 0); map.put("Text2", 1); map.put("Text3", 2); map.put("Text4", 0); 

It is necessary that it is sorted as follows:

 Key - Value: Text3 - 2 Text2 - 1 Text1 - 0 Text4 - 0 

or

 Text3 - 2 Text2 - 1 Text4 - 0 Text1 - 0 

Reported as a duplicate by participants pavel , Denis , aleksandr barakin , katso , Alex Nov 22 '16 at 1:24 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

1 answer 1

Maybe someone will be useful, here's how I did:

 private static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) { return map.entrySet() .stream() .sorted(Map.Entry.comparingByValue(Collections.reverseOrder())) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new )); }