Sorting HashMap by values in java

Let’s learn sorting hashmap by values in java.

Sorting hashmap by values in java

How to sort HashMap by value in java is one the common java interview question.

In java we cannot directly sort HashMap by value. Sorting a HashMap according to values can be done by writing our own Comparator which compares two elements based on values.

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

sorting hashmap by values in java

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.

Also read – arraylist in java

Then in 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 java program on sorting hashmap by values. In the below example agenda is to sort hashmap according to values, that is, units (car) sold.

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 SortHashMapByValue
{
   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());
      }
   }
   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


java sort hashmap by key

Here’s the java sort HashMap by key.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class SortHashMapByKey
{
   public static void main(String[] args)
   {
      HashMap<Integer, String> hm = new HashMap<Integer, String>();
      hm.put(9, "Apple");
      hm.put(14, "Orange");
      hm.put(2, "Mango");
      hm.put(98, "Pineapple");
      hm.put(5, "Watermelon");
      System.out.println("Before Sorting: ");
      Set set = hm.entrySet();
      Iterator iterate = set.iterator();
      while(iterate.hasNext())
      {
         Map.Entry me = (Map.Entry)iterate.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
      Map<Integer, String> map = new TreeMap<Integer, String>(hm);
      System.out.println("After Sorting: ");
      Set set2 = map.entrySet();
      Iterator iterate2 = set2.iterator();
      while(iterate2.hasNext())
      {
         Map.Entry me2 = (Map.Entry)iterate2.next();
         System.out.print(me2.getKey() + ": ");
         System.out.println(me2.getValue());
      }
   }
}


Output:

Before Sorting:
2: Mango
98: Pineapple
5: Watermelon
9: Apple
14: Orange
After Sorting:
2: Mango
5: Watermelon
9: Apple
14: Orange
98: Pineapple


treemap sort by value

As we know treemap is basically sorted based on its keys. To sort treemap by value create our own logic using 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


In this post we learnt sort hashmap by value and then by key. I hope you have understood the concept.

Sort hashmap by value and then by key is one of the common java interview question.