• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

How to Sort HashMap in Java by Keys

September 24, 2015 by javainterviewpoint 2 Comments

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

Other interesting articles which you may like …

  • Java HashMap clear() Method Example
  • Java HashMap clone() Method Example
  • Java HashMap containsKey(Object key) Method Example
  • Java HashMap containsValue(Object value) Example
  • Java HashMap get(Object key) Example
  • Java HashMap isEmpty() Example
  • Java HashMap keySet() Example
  • Java HashMap put(K key, V value) Example
  • Java HashMap putAll() Example
  • Java HashMap remove(Object o) Method Example
  • Java HashMap size() Example
  • Java HashMap values() Method Example

Filed Under: Core Java, Java Tagged With: comparator(), hashmap, Java, keys(), Sort, Sort HashMap, TreeMap

Comments

  1. Tainoor Bashir Manyar says

    March 18, 2019 at 6:36 pm

    What if key is String?

    Reply
    • javainterviewpoint says

      March 21, 2019 at 10:25 pm

      The code should work fine, even if the key is a String

      Reply

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·