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
1//----------------------------------------------------------------------
2// in ascending order:
3Map<String, Integer> unSortedMap = getUnSortedMap();
4
5System.out.println("Unsorted Map : " + unSortedMap);
6
7//LinkedHashMap preserve the ordering of elements in which they are inserted
8LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();
9
10unSortedMap.entrySet()
11 .stream()
12 .sorted(Map.Entry.comparingByValue())
13 .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
14
15System.out.println("Sorted Map : " + sortedMap);
16
17Output:
18
19Unsorted Map : {alex=1, charles=4, david=2, brian=5, elle=3}
20Sorted Map : {alex=1, david=2, elle=3, charles=4, brian=5}
21
22
23//----------------------------------------------------------------------
24// in descending order:
25Map<String, Integer> unSortedMap = getUnSortedMap();
26
27System.out.println("Unsorted Map : " + unSortedMap);
28
29//LinkedHashMap preserve the ordering of elements in which they are inserted
30LinkedHashMap<String, Integer> reverseSortedMap = new LinkedHashMap<>();
31
32//Use Comparator.reverseOrder() for reverse ordering
33unSortedMap.entrySet()
34 .stream()
35 .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
36 .forEachOrdered(x -> reverseSortedMap.put(x.getKey(), x.getValue()));
37
38System.out.println("Reverse Sorted Map : " + reverseSortedMap);
39
40Output:
41
42Unsorted Map : {alex=1, charles=4, david=2, brian=5, elle=3}
43Reverse Sorted Map : {brian=5, charles=4, elle=3, david=2, alex=1}
44