September 26, 2021

Sort HashMap Object Based on Key

There are different ways to sort the HashMap object based on key. 1: Using ArrayList. 2: Using TreeMap

1: Using ArrayList
Get the list of keys from HashMap object using keySet method.
Pass this set to ArrayList object
Use the inbuilt sort method: Collections.sort()

package com.chetasmind.mapPackage;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeMap;

public class SortHashMapBasedOnKey { 
		
      public static void main(String[] args) {
	           
            HashMap<String,String>obj = new HashMap<>();
            obj.put("Suresh", "Bangalore");
            obj.put("Rajesh", "Goa");
            obj.put("Neha", "Mangalore");
		         
            //Returns a Set view of the keys contained in this map.
            Set<String> set = obj.keySet();
		         
           //Creating ArrayList object from set
            ArrayList<String> arrObj = new ArrayList<>(set);
		         
            //Sorting the arraylist object.
            Collections.sort(arrObj);
		         
            System.out.println("\n  Display of Key, values in ascending order of keys.");
            for(String person: arrObj) {
                   System.out.print("\n Key is :"+person);
                   System.out.print("  Value is :"+obj.get(person));   
           } // End of for loop	        
      }
}

2: Using TreeMap object
Pass the HashMap object while creating the TreeMap object. While inserting, TreeMap object compares the key and inserts in ascending order of key. Add below code after the for loop ends.

TreeMap<String,String> treeMap = new TreeMap<>(obj);
set = treeMap.keySet();
			
System.out.println("\n Display of TreeMap object");
for(String person: set) {
     System.out.println();
     System.out.print("Key is :"+person);
     System.out.print("  Value is :"+treeMap.get(person));
}

Food for thought : If we need sorted key, then instead of HashMap object, we can create TreeMap object and add key, value to this object ? Answer is : Yes, You can. But in some real time applications, HashMap object is used in multiple places and only in one place you need sorted values of this object, then in this case, you can use TreeMap.

The above application is also present in my github repository.
If you are writing java applications for the first time, refer my Project structure article.

Leave a Reply

Your email address will not be published. Required fields are marked *