Sorting HashMap by values in java

Let’s learn sorting hashmap by values in java.

sorting hashmap by values in java

Sorting hashmap by values in java

In java we cannot directly sort HashMap by value. So sorting a HashMap according to values can be done by writing our own Comparator.

Also read – arraylist in java

This comparator takes Map.entry object and orders in increasing or decreasing by value.

In the below java program first we are getting entries by calling entrySet() method of class Map.

Here I have created sortByValue(hash) method which accepts entries as parameter.

Then inside sortByValue() method sort based on values using custom Comparator. In the next step convert set to a list.

Now using Collections.sort() method sort list by passing comparator value. Finally add entries in sorted order by creating LinkedHashMap.

Now let’s see a program on sorting hashmap by values in java or sort hashmap by value in ascending order,

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class HashMapByValue 
{
   public static void main(String[] args) 
   {
      HashMap<String, Integer> hash = new HashMap<String, Integer>(); 
      hash.put("Toyota", 78); 
      hash.put("Skoda", 69); 
      hash.put("Honda", 93); 
      hash.put("Audi", 59); 
      hash.put("Chevrolet", 39); 
      hash.put("Hyundai", 56); 
      Map<String, Integer> map = sortByValue(hash); 
      System.out.println("Sorting hashmap by values in java: ");
      // printing sorted HashMap 
      for(Map.Entry<String, Integer> me : map.entrySet()) 
      { 
         System.out.println("Key = " + me.getKey() + ", Value = " + me.getValue()); 
      }
   }

   // method sort HashMap by value 
   public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm) 
   { 
      // creating list from elements of HashMap
      List<Map.Entry<String, Integer> > list = 
new LinkedList<Map.Entry<String, Integer> >(hm.entrySet());

      // sorting list 
      Collections.sort(list, new Comparator<Map.Entry<String, Integer> >()
      { 
         public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) 
         { 
            return (o1.getValue()).compareTo(o2.getValue()); 
         } 
      }); 

      HashMap<String, Integer> ha = new LinkedHashMap<String, Integer>(); 
      for(Map.Entry<String, Integer> me : list) 
      { 
         ha.put(me.getKey(), me.getValue()); 
      } 
      return ha;
   }
}



Output:

Sorting hashmap by values in java:

Key = Chevrolet, Value = 39
Key = Hyundai, Value = 56
Key = Audi, Value = 59
Key = Skoda, Value = 69
Key = Toyota, Value = 78
Key = Honda, Value = 93

Sort hashmap by value in descending order java 8

To sort hashmap by value in java 8 streams use Map.Entry.comparingByValue() method which returns a comparator that compares Map.Entry in natural order on value.

On the other hand to sort hashmap by value in descending order in java 8 use Comparator.reverseOrder() method.

Comparator.reverseOrder() method returns a comparator that imposes reverse of the natural ordering.

The returned comparator is serializable and throws NullPointerException when comparing null.

Here’s the java program to sort HashMap by values.

import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class SortHashMapByValue 
{
   private static Map UnSortedMap() 
   {
      Map<String, Integer> hm = new HashMap<>();
      hm.put("lion", 19);
      hm.put("tiger", 20);
      hm.put("cheetah", 21);
      hm.put("bear", 22);
      hm.put("jaguar", 23);
      return hm;
   }

   public static void main(String[] args) 
   {
      System.out.println("Sort HashMap using Java8 streams");
      System.out.println("--------------------------------");
      sortByValue();
   }

   private static void sortByValue() 
   {
      Map<String, Integer> unsorted = UnSortedMap();
      System.out.println("Unsorted Map: " + unsorted);

      LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();
      unsorted.entrySet().stream().sorted(Map.Entry.comparingByValue())
         .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));

      System.out.println("Sorted Map: " + sortedMap); 
      LinkedHashMap<String, Integer> descendingOrder = new LinkedHashMap<>();
      unsorted.entrySet().stream().sorted(Map.Entry.
         comparingByValue(Comparator.reverseOrder()))
         .forEachOrdered(x -> descendingOrder.put(x.getKey(), x.getValue()));

      System.out.println("HashMap in descending order: " + descendingOrder);
   }
}


Output:

Sort HashMap using Java8 streams

Unsorted Map: {cheetah=21, bear=22, tiger=20, lion=19, jaguar=23}
Sorted Map: {lion=19, tiger=20, cheetah=21, bear=22, jaguar=23}
HashMap descending order: {jaguar=23, bear=22, cheetah=21, tiger=20, lion=19}

Reference: comparing by value – oracle docs, comparator reverse order docs oracle.

sort hashmap by key java 8

To sort hashmap by key in java 8 use comparingByKey() method of Map.Entry class.

In java 8 sort HashMap by keys first get a set of entry objects. Then in the next step convert entry objects into Stream.

After converting to Stream sort entry objects by passing Entry.comparingByKey() method.

In the last step collect sorted entry objects into LinkedHashMap. Since LinkedHashMap maintains insertion order.

Here’s sort hashmap by key java 8 in natural order,

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class SortHashMapByKey 
{
   public static void main(String[] args) 
   {
      Map<String, Integer> hm = new HashMap<>();
      hm.put("lion", 38);
      hm.put("tiger", 95);
      hm.put("cheetah", 84);
      hm.put("bear", 55);
      hm.put("jaguar", 59);
      System.out.println("Given hashmap: " + hm);
      Map<String, Integer> result = hm.entrySet().stream()
             .sorted(Map.Entry.comparingByKey())
             .collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,(oldValue, newValue) -> oldValue, LinkedHashMap::new));
      System.out.println("After sort hashmap by key java 8: ");
      System.out.println(result);
   }
}


Output:

Given hashmap: {cheetah=84, bear=55, tiger=95, lion=38, jaguar=59}
After sort hashmap by key java 8: {bear=55, cheetah=84, jaguar=59, lion=38, tiger=95}

treemap sort by value

As we know treemap is basically sorted based on its keys. To sort treemap by value use Comparator.

Also read – treemap in java

Here’s the complete code on treemap sort by value.

import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class SortTreeMapByValue 
{
   public static void main(String[] args) 
   {
      TreeMap<String, String> tm = new TreeMap<String, String>();
      tm.put("Key1", "lion");
      tm.put("Key2", "tiger");
      tm.put("Key3", "cheetah");
      tm.put("Key4", "bear");
      tm.put("Key5", "jaguar");
      Map sorted = sortingByValues(tm);
      Set set = sorted.entrySet();
      Iterator iterate = set.iterator();
      while(iterate.hasNext()) 
      {
         Map.Entry map = (Map.Entry)iterate.next();
         System.out.print(map.getKey() + ": ");
         System.out.println(map.getValue());
      }
   }

   public static <K, V extends Comparable<V>> Map<K, V> sortingByValues(final Map<K, V> map)
   {
      Comparator<K> comp = new Comparator<K>() 
      {
         public int compare(K k1, K k2) 
         {
            int compare = map.get(k1).compareTo(map.get(k2));
            if(compare == 0)
            {
               return 1;
            }
            else
            {
               return compare;
            }
         }
      };
      Map<K, V> byValues = new TreeMap<K, V>(comp);
      byValues.putAll(map);
      return byValues;
   }
}


Output:

Key4: bear
Key3: cheetah
Key5: jaguar
Key1: lion
Key2: tiger