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
1import java.util.Collections;
2import java.util.Comparator;
3import java.util.HashMap;
4import java.util.LinkedHashMap;
5import java.util.LinkedList;
6import java.util.List;
7import java.util.Map;
8public class SortHashMapByValue
9{
10 public static void main(String[] args)
11 {
12 HashMap<String, Integer> hash = new HashMap<String, Integer>();
13 hash.put("Toyota", 78);
14 hash.put("Skoda", 69);
15 hash.put("Honda", 93);
16 hash.put("Audi", 59);
17 hash.put("Chevrolet", 39);
18 hash.put("Hyundai", 56);
19 Map<String, Integer> map = sortByValue(hash);
20 System.out.println("Sorting hashmap by values in java: ");
21 // printing sorted HashMap
22 for(Map.Entry<String, Integer> me : map.entrySet())
23 {
24 System.out.println("Key = " + me.getKey() + ", Value = " + me.getValue());
25 }
26 }
27 public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm)
28 {
29 // creating list from elements of HashMap
30 List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(hm.entrySet());
31 // sorting list
32 Collections.sort(list, new Comparator<Map.Entry<String, Integer>>()
33 {
34 public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2)
35 {
36 return (o1.getValue()).compareTo(o2.getValue());
37 }
38 });
39 HashMap<String, Integer> ha = new LinkedHashMap<String, Integer>();
40 for(Map.Entry<String, Integer> me : list)
41 {
42 ha.put(me.getKey(), me.getValue());
43 }
44 return ha;
45 }
46}