sort a map by value java code example
Example 1: Java sort Map by values
Map<String, Integer> unSortedMap = getUnSortedMap();
System.out.println("Unsorted Map : " + unSortedMap);
LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();
unSortedMap.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue())
.forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
System.out.println("Sorted Map : " + sortedMap);
Output:
Unsorted Map : {alex=1, charles=4, david=2, brian=5, elle=3}
Sorted Map : {alex=1, david=2, elle=3, charles=4, brian=5}
Map<String, Integer> unSortedMap = getUnSortedMap();
System.out.println("Unsorted Map : " + unSortedMap);
LinkedHashMap<String, Integer> reverseSortedMap = new LinkedHashMap<>();
unSortedMap.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.forEachOrdered(x -> reverseSortedMap.put(x.getKey(), x.getValue()));
System.out.println("Reverse Sorted Map : " + reverseSortedMap);
Output:
Unsorted Map : {alex=1, charles=4, david=2, brian=5, elle=3}
Reverse Sorted Map : {brian=5, charles=4, elle=3, david=2, alex=1}
Example 2: hashmap sort ascending
LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();
unSortedMap.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));