How to Sort HashMap in Java by Keys

We all know that HashMap will not save key-value pairs in any sort of order neither preserve the insertion order. In this tutorial we will learn how to sort a HashMap based on Keys. We will be using two approaches.

  1. TreeMap Collection class (Which has in-built support for sorting the elements using Comparable and Comparator  Interface)
  2. Implementing the Comparator Interface
  3. Using Collections.sort() method

1. HashMap Sorting by Keys Example – Using TreeMap

In this example we will sort the keys of the HashMap using TreeMap. Sorting a HashMap keys using a TreeMap is very simple, simply add the unsorted hashMap(unsortedMap) to the TreeMap to get it sorted.

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

public class SortByKeysHashMapExample 
{
    public static void main(String[] args) {

        Map<Integer, String> unsortedMap = new HashMap<Integer, String>();
        unsortedMap.put(5, "asd");
        unsortedMap.put(1, "cfd");
        unsortedMap.put(7, "gdf");
        unsortedMap.put(55, "qwe");
        unsortedMap.put(66, "weq");
        unsortedMap.put(3, "wer");
        unsortedMap.put(8, "yes");
        unsortedMap.put(93, "nsa");
        unsortedMap.put(50, "tes");
        unsortedMap.put(12, "mds");
        unsortedMap.put(43, "fsa");
        
        //Print the Elements of the Map before Sorting
        System.out.println("Elements of the HashMap before Sorting");
        printMap(unsortedMap);
        
        //Create a Treemap of unsortedMap to get it sorted
        Map<Integer,String> sortedMap = new TreeMap<Integer,String>(unsortedMap);
        
        //Print the Elements of the Map after Sorting
        System.out.println("Elements of the HashMap after Sorting");
        printMap(sortedMap);
        
    }

    public static void printMap(Map<Integer, String> map) {
        System.out.println("**************************************");
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey() 
                                      + " Value : " + entry.getValue());
        }
        System.out.println();
    }
}

Output :

Elements of the HashMap before Sorting
**************************************
Key : 50 Value : tes
Key : 1 Value : cfd
Key : 3 Value : wer
Key : 55 Value : qwe
Key : 5 Value : asd
Key : 66 Value : weq
Key : 7 Value : gdf
Key : 93 Value : nsa
Key : 8 Value : yes
Key : 43 Value : fsa
Key : 12 Value : mds

Elements of the HashMap after Sorting
**************************************
Key : 1 Value : cfd
Key : 3 Value : wer
Key : 5 Value : asd
Key : 7 Value : gdf
Key : 8 Value : yes
Key : 12 Value : mds
Key : 43 Value : fsa
Key : 50 Value : tes
Key : 55 Value : qwe
Key : 66 Value : weq
Key : 93 Value : nsa

2. HashMap Sorting by Keys Example – Using TreeMap and Comparator

We will be overriding the compare() method of the Comparator 

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

public class SortByKeysHashMapExample 
{
    public static void main(String[] args) {

        Map<Integer, String> unsortedMap = new HashMap<Integer, String>();
        unsortedMap.put(5, "asd");
        unsortedMap.put(1, "cfd");
        unsortedMap.put(7, "gdf");
        unsortedMap.put(55, "qwe");
        unsortedMap.put(66, "weq");
        unsortedMap.put(3, "wer");
        unsortedMap.put(8, "yes");
        unsortedMap.put(93, "nsa");
        unsortedMap.put(50, "tes");
        unsortedMap.put(12, "mds");
        unsortedMap.put(43, "fsa");

      //Print the Elements of the Map before Sorting
        System.out.println("Elements of the HashMap before Sorting");
        printMap(unsortedMap);
        
        Map<Integer,String> sortedMap = 
                new TreeMap<Integer,String>(new Comparator<Integer>()
        {
            @Override
            public int compare(Integer i1, Integer i2)
            {
                return i1.compareTo(i2);
            }
        }
                );
        
        sortedMap.putAll(unsortedMap);
        //Print the Elements of the Map after Sorting
        System.out.println("Elements of the HashMap after Sorting");
        printMap(sortedMap);
        
    }

    public static void printMap(Map<Integer, String> map) {
        System.out.println("**************************************");
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey() 
                                      + " Value : " + entry.getValue());
        }
        System.out.println();
    }
}

Output :

Elements of the HashMap before Sorting
**************************************
Key : 50 Value : tes
Key : 1 Value : cfd
Key : 3 Value : wer
Key : 55 Value : qwe
Key : 5 Value : asd
Key : 66 Value : weq
Key : 7 Value : gdf
Key : 93 Value : nsa
Key : 8 Value : yes
Key : 43 Value : fsa
Key : 12 Value : mds

Elements of the HashMap after Sorting
**************************************
Key : 1 Value : cfd
Key : 3 Value : wer
Key : 5 Value : asd
Key : 7 Value : gdf
Key : 8 Value : yes
Key : 12 Value : mds
Key : 43 Value : fsa
Key : 50 Value : tes
Key : 55 Value : qwe
Key : 66 Value : weq
Key : 93 Value : nsa

3. HashMap Sorting by Keys Example – Collections.sort() method

In this approach we will be getting the EntrySet and store it to a List(sortedList)and pass the list along with the comparator to Collections.sort() method. Finally add the sortedList to the LinkedHashMap(sortedMap) as it will maintain the insertion order.

package com.javainterviewpoint.HashMap;

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

public class SortByKeysHashMapExample
{
    public static void main(String[] args) {

        Map<Integer, String> unsortedMap = new HashMap<Integer, String>();
        unsortedMap.put(5, "asd");
        unsortedMap.put(1, "cfd");
        unsortedMap.put(7, "gdf");
        unsortedMap.put(55, "qwe");
        unsortedMap.put(66, "weq");
        unsortedMap.put(3, "wer");
        unsortedMap.put(8, "yes");
        unsortedMap.put(93, "nsa");
        unsortedMap.put(50, "tes");
        unsortedMap.put(12, "mds");
        unsortedMap.put(43, "fsa");
        
        //Print the Elements of the Map before Sorting
        System.out.println("Elements of the HashMap before Sorting");
        printMap(unsortedMap);
        
        List<Entry<Integer,String>> unsortedList = new ArrayList<Entry<Integer,String>>(unsortedMap.entrySet());
        
        Collections.sort(unsortedList,new Comparator<Entry<Integer,String>>()
                {
                    @Override
                    public int compare(Entry<Integer,String> e1,Entry<Integer,String> e2)
                    {
                        return e1.getKey().compareTo(e2.getKey());
                    }
                }
                );
        Map<Integer,String> sortedMap = new LinkedHashMap<Integer,String>();
        
        for(Entry<Integer,String> entry:unsortedList){
            sortedMap.put(entry.getKey(),entry.getValue());
        }
        //Print the Elements of the Map after Sorting
        System.out.println("Elements of the HashMap after Sorting");
        printMap(sortedMap);
        
    }

    public static void printMap(Map<Integer, String> map) {
        System.out.println("**************************************");
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey() 
                                      + " Value : " + entry.getValue());
        }
        System.out.println();
    }
}

Output :

Elements of the HashMap before Sorting
**************************************
Key : 50 Value : tes
Key : 1 Value : cfd
Key : 3 Value : wer
Key : 55 Value : qwe
Key : 5 Value : asd
Key : 66 Value : weq
Key : 7 Value : gdf
Key : 93 Value : nsa
Key : 8 Value : yes
Key : 43 Value : fsa
Key : 12 Value : mds

Elements of the HashMap after Sorting
**************************************
Key : 1 Value : cfd
Key : 3 Value : wer
Key : 5 Value : asd
Key : 7 Value : gdf
Key : 8 Value : yes
Key : 12 Value : mds
Key : 43 Value : fsa
Key : 50 Value : tes
Key : 55 Value : qwe
Key : 66 Value : weq
Key : 93 Value : nsa

How to Sort HashMap having Object Keys ?

We have learnt how to sort Wrapper Objects, but in the real world situations you will be in a situation to sort object based on the particular attribute lets now see how we can achieve this.

Lets take a class Car which has two attributes color and wheels, we implement sorting of Car object based on wheels attribute

Car.java

public class Car 
{
    private String color;
    private Integer wheels;
    
    public Car(String color, int wheels) {
        this.color = color;
        this.wheels = wheels;
    }
    
    public String getColor() {
        return color;
    }
    public Integer getWheels() {
        return wheels;
    }
    @Override
    public String toString()
    {
        return ""+color+""+wheels;
    }
}

SortObjectKeyHashMapExample.java

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

public class SortObjectKeyHashMapExample 
{
    public static void main(String args[])
    {
        Map<Car,String> unsortedMap = new HashMap<Car,String>();
        
        Car c1 = new Car("Red",3);
        Car c2 = new Car("Blue",1);
        Car c3 = new Car("Green",4);
        Car c4 = new Car("Yellow",2);
        
        unsortedMap.put(c1, "Red Car");
        unsortedMap.put(c2, "Blue Car");
        unsortedMap.put(c3, "Green Car");
        unsortedMap.put(c4, "Yellow Car");
        
        //Print the Elements of the Map before Sorting
        System.out.println("Elements of the HashMap before Sorting");
        printMap(unsortedMap);
        
        Map<Car,String> sortedMap = new TreeMap<Car,String>(
                new Comparator()
                {
                    @Override
                    public int compare(Car c1,Car c2)
                    {
                        return c1.getWheels().compareTo(c2.getWheels());
                    }
                });
        sortedMap.putAll(unsortedMap);
        //Print the Elements of the Map after Sorting
        System.out.println("Elements of the HashMap after Sorting");
        printMap(sortedMap);
    }
    public static void printMap(Map<Car, String> map) {
        System.out.println("**************************************");
        for (Entry<Car, String> entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey() 
                                      + "  Value : " + entry.getValue());
        }
        System.out.println();
    }
}

Output : 

Elements of the HashMap before Sorting
**************************************
Key : Blue1  Value : Blue Car
Key : Yellow2  Value : Yellow Car
Key : Green4  Value : Green Car
Key : Red3  Value : Red Car

Elements of the HashMap after Sorting
**************************************
Key : Blue1  Value : Blue Car
Key : Yellow2  Value : Yellow Car
Key : Red3  Value : Red Car
Key : Green4  Value : Green Car

Note :

If you want the HashMap keys to be sorted in Descending (Reverse) order just reverse the condition like below

return c2.getWheels().compareTo(c1.getWheels());

Leave a Reply

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