1Map<String, Integer> unSortedMap = getUnSortedMap();
2
3System.out.println("Unsorted Map : " + unSortedMap);
4
5//LinkedHashMap preserve the ordering of elements in which they are inserted
6LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();
7
8unSortedMap.entrySet()
9 .stream()
10 .sorted(Map.Entry.comparingByValue())
11 .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
12
13System.out.println("Sorted Map : " + sortedMap);
14
15Output:
16
17Unsorted Map : {alex=1, charles=4, david=2, brian=5, elle=3}
18Sorted Map : {alex=1, david=2, elle=3, charles=4, brian=5}
19