Sorting HashMap by values in java

Let’s learn sorting HashMap by values in java.

Sorting HashMap by values in java

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.

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.

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


Also read – operators in java