sort by value map + java8 code example

Example 1: Java sort Map by values

//----------------------------------------------------------------------
// in ascending order:
Map<String, Integer> unSortedMap = getUnSortedMap();
         
System.out.println("Unsorted Map : " + unSortedMap);
 
//LinkedHashMap preserve the ordering of elements in which they are inserted
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}


//----------------------------------------------------------------------
// in descending order:
Map<String, Integer> unSortedMap = getUnSortedMap();
         
System.out.println("Unsorted Map : " + unSortedMap);
 
//LinkedHashMap preserve the ordering of elements in which they are inserted
LinkedHashMap<String, Integer> reverseSortedMap = new LinkedHashMap<>();
 
//Use Comparator.reverseOrder() for reverse ordering
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: sort a map based on keys and values using java 8

Map< Integer, String> map=new HashMap<Integer, String>();

map.put(101, "Hemendra");
map.put(99, "Andrew");
map.put(103, "Anish");
map.put(18, "Mohan");
map.put(11, "Christine");
map.put(109, "Rebeca");
map.put(111, "David");
map.put(19, "Rahim");
map.put(10, "Krishna");

Required to sort the map:

1. On the basis of keys:

[10=Krishna, 11=Christine, 18=Mohan, 19=Rahim, 99=Andrew, 101=Hemendra, 103=Anish, 109=Rebeca, 111=David]

2. On the basis of values:

[99=Andrew, 103=Anish, 11=Christine, 111=David, 101=Hemendra, 10=Krishna, 18=Mohan, 19=Rahim, 109=Rebeca]

Solution:

System.out.println(map.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toList()));
System.out.println(map.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toList()));

Tags:

Java Example