Sort Hashmap By Value

Hi!! Welcome to flower brackets blog. Today we are going to learn sort hashmap by value.

Sort HashMap by Value

So to sort a hashmap we have to insert some key and values and create a linkedlist from the map entries.

Also Read – Merge Sort Java

Hashmap does not maintain order by default. If there is a need we need to sort it explicitly based on requirement.

Now let’s us see code implementation of hashmap sort by key,

Java hashmap sort by key

Let’s see how to sort a hashmap by key using Treemap collection class,

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

public class HashMapByKey 
{
   public static void main(String[] args) 
   {
      HashMap<Integer, String> hm = new HashMap<Integer, String>();
      hm.put(4, "dhoni");
      hm.put(3, "virat");
      hm.put(6, "ajith");
      hm.put(2, "bharath");
      hm.put(1, "chetesh");
      hm.put(5, "kapil");
      hm.put(7, "ishant");

      System.out.println("Java sorted map by key - Before Sorting : ");
      Set set = hm.entrySet();
      Iterator ir = set.iterator();
      while(ir.hasNext())
      {
         Map.Entry me = (Map.Entry)ir.next();
         System.out.print(me.getKey() + " : ");
         System.out.println(me.getValue());
      }
      Map<Integer, String> map = new TreeMap<Integer, String>(hm); 
      System.out.println("Java sorted map by key - After Sorting : ");
      Set set2 = map.entrySet();
      Iterator ir2 = set2.iterator();
      while(ir2.hasNext())
      {
         Map.Entry me2 = (Map.Entry)ir2.next();
         System.out.print(me2.getKey() + " : ");
         System.out.println(me2.getValue());
      }
   }
}

Output :

Java sorted map by key - Before Sorting : 
4 : dhoni
3 : virat
6 : ajith
2 : bharath
1 : chetesh
5 : kapil
7 : ishant
Java sorted map by key - After Sorting : 
1 : chetesh
2 : bharath
3 : virat
4 : dhoni
5 : kapil
6 : ajith
7 : ishant


Sort hashmap by value java – using comparator

To sort a hashmap by value first we need to store entry value set in list and sort list on basis of values.

Also Read – Palindrome Java

Next we have to retrieve value and key from list and place in new hashmap. Lastly hashmap should be sorted according to values.

import java.text.ParseException;
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 HashMapExample
{
   public static void main(String[] args) throws ParseException 
   {
      HashMap<String, Integer> hm = new HashMap<String, Integer>();
		 
      // add data into hashmap
      hm.put("Orange", 4);
      hm.put("Mango", 3);
      hm.put("Strawberry", 6);
      hm.put("Cherry", 2);
      hm.put("Apple", 1);
      hm.put("Grape", 7);
      Map<String, Integer> map = hashByValue(hm);
 
      System.out.println("Sorting a hashmap by value in java - ");
      // printing sorted hashmap
      for(Map.Entry<String, Integer> me : map.entrySet())
      {
         System.out.println("Key = " + me.getKey() + ", Value = " + me.getValue());
      }
   }
	
   // this function sorts hashmap by value
   public static HashMap<String, Integer> hashByValue(HashMap<String, Integer> hm)
   {
      // creating list from hashmap elements
      List<Map.Entry<String, Integer>> li = new LinkedList<Map.Entry<String, Integer> >(hm.entrySet());
 
      // here we are sorting the list
      Collections.sort(li, 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());
         }
      });
         
      // add data from sorted list to hashmap 
      HashMap<String, Integer> ha = new LinkedHashMap<String, Integer>();
      for(Map.Entry<String, Integer> aa : li) 
      {
         ha.put(aa.getKey(), aa.getValue());
      }
      return ha;
   }
}

Output:

Sorting a hashmap by value in java - 
Key = Apple, Value = 1
Key = Cherry, Value = 2
Key = Mango, Value = 3
Key = Orange, Value = 4
Key = Strawberry, Value = 6
Key = Grape, Value = 7


Java map comparator – generic types

Now we will learn treemap sort by value in descending order,

import java.util.Comparator;
import java.util.HashMap;
import java.util.TreeMap;

public class HashMapByValue 
{
   public static void main(String[] args) 
   {
      // String and Integer HashMap
      HashMap<String, Integer> hm = new HashMap<String, Integer>();
      hm.put("aa", 1);
      hm.put("bb", 3);
      hm.put("cc", 5);
      hm.put("dd", 4);
      hm.put("ee", 2);
      System.out.println(hm);

      Comparator<String> com = new ValueComparator<String, Integer>(hm);
      TreeMap<String, Integer> output = new TreeMap<String, Integer>(com);
      output.putAll(hm);

      System.out.println(output);

      // Integer and Integer HashMap 
      HashMap<Integer, Integer> hm2 = new HashMap<Integer, Integer>();
      hm2.put(1, 11);
      hm2.put(2, 31);
      hm2.put(3, 51);
      hm2.put(4, 41);
      hm2.put(5, 21);
      System.out.println(hm2);

      Comparator<Integer> com2 = new ValueComparator<Integer, Integer>(hm2);
      TreeMap<Integer, Integer> output2 = new TreeMap<Integer, Integer>(com2);
      output2.putAll(hm2);

      System.out.println(output2);
   }
}

// comparator using generic type
class ValueComparator<K, V extends Comparable<V>> implements Comparator<K>
{
   HashMap<K, V> map = new HashMap<K, V>();

   public ValueComparator(HashMap<K, V> map)
   {
      this.map.putAll(map);
   }

   @Override
   public int compare(K s1, K s2) 
   {
      // java sort hashmap by value descending
      return -map.get(s1).compareTo(map.get(s2));
   }
}

Output :

{aa=1, bb=3, cc=5, dd=4, ee=2}
{cc=5, dd=4, bb=3, ee=2, aa=1}
{1=11, 2=31, 3=51, 4=41, 5=21}
{3=51, 4=41, 2=31, 5=21, 1=11}


Conclusion

That’s it guys. So this is all about how to sort hashmap by value in java. I hope you have understood how to sort hashmap by value and key in java.

You can subscribe to my blog flower brackets if you haven’t already.

If you like this post, do share it across social networks.

Related Posts