How to sort HashMap in java by keys and values

HashMap does not preserve order of element but what if you want to sort it by keys or values. In this post, we will see how to sort HashMap by keys or values.

Java HashMap tutorial:

    HashMap in javaHashMap internal workinghash and indexfor method in HashMaphashcode and equals in javasort HashMap by keys and valuesDifference between HashMap and HashSetDifference between HashMap and HashtableHow to iterate over HashMap

Sorting by Keys: 

Sorting by keys can be easily done using TreeMap. You just need to pass HashMap to the constructor of TreeMap.
TreeMap map=new TreeMap(Map hm);

Sorting by values:

We can use Comparator to sort it by values.

Sorting by Keys example :

Create Country.java as below. It should implement Comparable interface
package org.arpit.java2blog;  
public class Country implements Comparable {  
  
 String name;  
 long population;  
   
 public Country(String name, long population) {  
  super();  
  this.name = name;  
  this.population = population;  
 }  
 public String getName() {  
  return name;  
 }  
 public void setName(String name) {  
  this.name = name;  
 }  
 public long getPopulation() {  
  return population;  
 }  
 public void setPopulation(long population) {  
  this.population = population;  
 }
@Override
public int compareTo(Object o) {
    Country country=(Country) o;
 return this.getName().compareTo(country.getName());
}  
       
}  

Create TreeMapCompMain.java as below:
package org.arpit.java2blog;

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

public class TreeMapCompMain {

 public static void main(String[] args)
 {
  Country india=new Country("India",1000);  
        Country japan=new Country("Japan",10000);  
            
        Country france=new Country("France",2000);  
        Country russia=new Country("Russia",20000);  
            
        HashMap<Country, String> countryCapitalMap=new HashMap<Country,String>();  
        countryCapitalMap.put(india,"Delhi");  
        countryCapitalMap.put(japan,"Tokyo");  
        countryCapitalMap.put(france,"Paris");  
        countryCapitalMap.put(russia,"Moscow");  
        
        System.out.println("Sorting HashMap by passing it to TreeMap constructor");
        TreeMap<Country,String> sortedTreeMapCountryCapital=new  TreeMap<Country,String> (countryCapitalMap);
        Iterator<Country> countryCapitalIter=sortedTreeMapCountryCapital.keySet().iterator();//put debug point at this line  
        while(countryCapitalIter.hasNext())  
        {  
            Country countryObj=countryCapitalIter.next();  
            String capital=countryCapitalMap.get(countryObj);  
            System.out.println(countryObj.getName()+"----"+capital);  
            }  
        }  

}

When you run program, you will get below output:
Sorting HashMap by passing it to TreeMap constructor
France----Paris
India----Delhi
Japan----Tokyo
Russia----Moscow

Sorting by values example: 

Here we will sort HashMap by its values. Here I am taking HashMap <String,String> to make example simpler.
Example:
package org.arpit.java2blog;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

public class HashMapMain {

 public static void main(String args[]) {
  // HashMap with Country name as key and capital as value
  // HashMap stores elements in key value pairs
  HashMap<String, String> countryCapitalMap = new HashMap<String, String>();

  countryCapitalMap.put("Japan", "Tokyo");
  countryCapitalMap.put("France", "Paris");
  countryCapitalMap.put("Russia", "Moscow");
  countryCapitalMap.put("India", "Delhi");

  System.out.println("-----------------------------");
  // Iterating HashMap Using keySet() and for each loop
  System.out.println("Before Sorting");
  System.out.println("-----------------------------");
  for (String countryKey : countryCapitalMap.keySet()) {
   System.out.println("Country:" + countryKey + " and  Capital:" + countryCapitalMap.get(countryKey));

  }
  
  Set<Entry<String, String>> countryCapitalEntrySet=countryCapitalMap.entrySet();
  
  List<Entry<String, String>> entryList=new ArrayList<Entry<String, String>>(countryCapitalEntrySet);
  
  Collections.sort(entryList,new Comparator<Entry<String,String>>() {

   @Override
   public int compare(Entry<String,String> o1, Entry<String,String> o2) {
    return o1.getValue().compareTo(o2.getValue());
   }
  });
  System.out.println("-----------------------------");
     
  // Using LinkedHashMop to keep entries in sorted order
  LinkedHashMap<String,String> sortedHashMap=new LinkedHashMap<String,String>();
  for (Entry<String,String> entry:entryList) {
   sortedHashMap.put(entry.getKey(), entry.getValue());
  }
  
  System.out.println("After Sorting");
  System.out.println("-----------------------------");
  // Iterating sortedHashMap Using keySet() and for each loop
  
  for (String countryKey : sortedHashMap.keySet()) {
   System.out.println("Country:" + countryKey + " and  Capital:" + sortedHashMap.get(countryKey));

  }
 }
}
When you run above program, you will get below output
-----------------------------
Before Sorting
-----------------------------
Country:France and  Capital:Paris
Country:Russia and  Capital:Moscow
Country:Japan and  Capital:Tokyo
Country:India and  Capital:Delhi
-----------------------------
After Sorting
-----------------------------
Country:India and  Capital:Delhi
Country:Russia and  Capital:Moscow
Country:France and  Capital:Paris
Country:Japan and  Capital:Tokyo

Explanation:

  1. Extract key set from HashMap using keySet() method.
  2. Create ArrayList from above set
  3. Sort above ArrayList using Comparator
  4. Create LinkedHashMap from Sorted list

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012