We can short a Map using java 8 and Java very easily let’s check out the code.
Shorting Map using Java 7
public static void main(String args[]) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Durgesh", 22);
map.put("Amit", 10);
map.put("Rajeev", 34);
map.put("Sumanth", 99);
map.put("Leonia", 43);
sortAndPrintMapUsinglegacy(map);
}
private static void sortAndPrintMapUsinglegacy(Map<String, Integer> map) {
//Getting Entry Object of map to List so that we can sort them
List<Map.Entry<String, Integer>> entryList = new ArrayList(map.entrySet());
//Sorting the list by value
entryList.sort((o1,o2) ->{
//Sorting in ascending order of value
return o1.getValue() - o2.getValue();
});
//Creating a Linked Hashmap so that insertion order will be maintained.
//As we need to maintain the sorted order as it is in list.
Map<String, Integer> finalMap = new LinkedHashMap<String, Integer>();
//Adding element from entrylist to linkedHashmap
for (Map.Entry<String, Integer> entry : entryList) {
finalMap.put(entry.getKey(), entry.getValue());
}
//Printing the map
System.out.println(finalMap);
}
Output of the above code is
{Amit=10, Durgesh=22, Rajeev=34, Leonia=43, Sumanth=99}Shorting Map using Java 8
public static void main(String args[]) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Durgesh", 22);
map.put("Amit", 10);
map.put("Rajeev", 34);
map.put("Sumanth", 99);
map.put("Leonia", 43);
sortAndPrintMapUsingJava8(map);
}
private static void sortAndPrintMapUsingJava8(Map<String, Integer> map) {
//Getting Entry Object of map to List so that we can sort them
// and creating the stream of sorted sets
Map<String, Integer> finalMap = map.entrySet().stream()
//Sorting in ascending order of value
.sorted(Comparator.comparing(Map.Entry::getValue))
//Creating a Linked Hashmap so that insertion order will be maintained.
//As we need to maintain the sorted order as it is in list.
//Adding element from entrylist to linkedHashmap
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (x,y) -> y, LinkedHashMap::new));
//Printing the map
System.out.println(finalMap);
}
Here we used (x,y)->y which is mapper function which will map same value when keys are equal.
Output of the above code is
{Amit=10, Durgesh=22, Rajeev=34, Leonia=43, Sumanth=99}Conclusion
Here we learned the ways of sorting HashMap on value using Java 8 and Legacy.

