How to sort a Map by Values in Java 8

Lets say you have Map<String,Integer> map = new HashMap<>() and now we want to sort the map (ascending / descending ) based on values. So we can use stream to do that in java 1.8+


//Ascending order 

Map<String, Integer> sortedMap = map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));


// descending order

  final List<Map.Entry<String, Integer>> reverseSortedMap = map.entrySet()
.stream()       .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
               

This will come handy when you can use TreeMap which sorts using key but not value.