Sorting HashMap by values in java

Today we are going to learn sorting hashmap by values in java.

sorting hashmap by values in java

Sorting hashmap by values in java

In sorting a Hashmap according to values first we have to store entry set in a list.

Also read – arraylist in java

Then we have to fetch value and key from list and place in hashmap. In this hashmap sorting takes place according to values.

Now let’s see a java program,

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); 

      // 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:

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