BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

How to sort HashMap in Java by Keys and Values

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

As we know that HashMap doesn’t preserve any order by default. If there is a need we need to sort it explicitly based on the requirement. In this tutorial we will learn how to sort HashMap by keys using TreeMap and by values using Comparator.

HashMap Sorting by Keys

In this example we are sorting the HashMap based on the keys using the TreeMap collection class.

package beginnersbook.com;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.Set;
import java.util.Iterator;

public class Details {

    public static void main(String[] args) {

         HashMap<Integer, String> hmap = new HashMap<Integer, String>();
         hmap.put(5, "A");
         hmap.put(11, "C");
         hmap.put(4, "Z");
         hmap.put(77, "Y");
         hmap.put(9, "P");
         hmap.put(66, "Q");
         hmap.put(0, "R");

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

Output:

Before Sorting:
0: R
4: Z
5: A
66: Q
9: P
77: Y
11: C
After Sorting:
0: R
4: Z
5: A
9: P
11: C
66: Q
77: Y

HashMap Sorting by Values

In this example we are sorting HashMap by values using Comparator.

package beginnersbook.com;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HMapSortingByvalues {
  public static void main(String[] args) {
      HashMap<Integer, String> hmap = new HashMap<Integer, String>();
      hmap.put(5, "A");
      hmap.put(11, "C");
      hmap.put(4, "Z");
      hmap.put(77, "Y");
      hmap.put(9, "P");
      hmap.put(66, "Q");
      hmap.put(0, "R");
      System.out.println("Before Sorting:");
      Set set = hmap.entrySet();
      Iterator iterator = set.iterator();
      while(iterator.hasNext()) {
           Map.Entry me = (Map.Entry)iterator.next();
           System.out.print(me.getKey() + ": ");
           System.out.println(me.getValue());
      }
      Map<Integer, String> map = sortByValues(hmap); 
      System.out.println("After Sorting:");
      Set set2 = map.entrySet();
      Iterator iterator2 = set2.iterator();
      while(iterator2.hasNext()) {
           Map.Entry me2 = (Map.Entry)iterator2.next();
           System.out.print(me2.getKey() + ": ");
           System.out.println(me2.getValue());
      }
  }

  private static HashMap sortByValues(HashMap map) { 
       List list = new LinkedList(map.entrySet());
       // Defined Custom Comparator here
       Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
               return ((Comparable) ((Map.Entry) (o1)).getValue())
                  .compareTo(((Map.Entry) (o2)).getValue());
            }
       });

       // Here I am copying the sorted list in HashMap
       // using LinkedHashMap to preserve the insertion order
       HashMap sortedHashMap = new LinkedHashMap();
       for (Iterator it = list.iterator(); it.hasNext();) {
              Map.Entry entry = (Map.Entry) it.next();
              sortedHashMap.put(entry.getKey(), entry.getValue());
       } 
       return sortedHashMap;
  }
}

Output:

Before Sorting:
0: R
4: Z
5: A
66: Q
9: P
77: Y
11: C
After Sorting:
5: A
11: C
9: P
66: Q
0: R
77: Y
4: Z

References:

  • HashMap Javadoc
  • Comparator Documentation
  • LinkedHashMap Javadoc
  • TreeMap docs

Top Related Articles:

  1. How to loop LinkedList in Java
  2. Java 8 – Filter null values from a Stream
  3. How to sort Hashtable in java
  4. How to synchronize HashMap in Java with example
  5. How to serialize HashMap in java

Tags: Collections, Java-HashMap

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Naresh says

    April 28, 2015 at 2:43 PM

    Note: below program will work, no need to worry about generics.
    import java.util.*;

    public class SortHashMapValues{
    public static void main(String []args){
    Map map=new HashMap();
    map.put(“one”,1);
    map.put(“ten”,10);
    map.put(“three”,3);
    map.put(“two”,2);

    List list=new ArrayList(map.entrySet());

    Collections.sort(list,new Comparator(){
    public int compare(Object obj1, Object obj2){
    return ((Comparable)((Map.Entry)(obj1)).getValue

    ()).compareTo(((Map.Entry)(obj2)).getValue());
    }
    });
    System.out.println(list);
    }
    }

    Reply
  2. Grupojrc says

    September 10, 2015 at 3:44 PM

    Hello at “HashMap Sorting by Values” if you add:
    hmap.put(900, “Ó”);
    hmap.put(9, “é”);

    The result is:
    After Sorting:
    5: A
    11: C
    66: Q
    0: R
    77: Y
    4: Z
    900: Ó
    9: é

    Is not correct.

    Reply
  3. John says

    December 23, 2015 at 7:14 PM

    Hello,

    Sorting by Keys sorted ascending, how can I sort descending?
    could you pls send a example?
    I usually visit your site, thank you

    Reply
    • Nick says

      November 4, 2016 at 9:13 PM

      To switch the sort order from ascending to descending, simply make the following change to the Comparator (swaps the order in which the objects are compared, the only change being 02.getValue is called before 01.getValue).

      Collections.sort(list, new Comparator() {
      public int compare(Object o1, Object o2) {
      return ((Comparable) ((Map.Entry) (o2)).getValue())
      .compareTo(((Map.Entry) (o1)).getValue());
      }

      Reply
      • Rohit says

        June 28, 2017 at 1:31 AM

        The guy was asking for key based sorting. Read the question at least.

        Reply

Leave a Reply Cancel reply

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

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap