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 Hashtable in java

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

Hashtable doesn’t preserve the insertion order, neither it sorts the inserted data based on keys or values. Which means no matter what keys & values you insert into Hashtable, the result would not be in any particular order.

For example: Lets have a look at the below program and its output:

import java.util.*;
public class HashtableDemo
{
    public static void main(String args[])
    {
       Hashtable<Integer, String> ht= new Hashtable<Integer, String>();
       ht.put(10, "Chaitanya");
       ht.put(1, "Ajeet");
       ht.put(11, "Test");
       ht.put(9, "Demo");
       ht.put(3, "Anuj");
 
       // Get a set of the entries
       Set set = ht.entrySet();
       // Get an iterator
       Iterator i = set.iterator();
       // Display elements
       while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
   }
}

Output:

10: Chaitanya
9: Demo
3: Anuj
1: Ajeet
11: Test

As you can see that the output key-value pairs are in random order. Neither we got insertion order nor the values are sorted based on keys or values.

The solution

The are ways to sort Hashtable using Collections.list and Collections.sort, however best thing to do is use LinkedHashMap or TreeMap.

Use LinkedHashMap: When you want to preserve the insertion order.
Use TreeMap: When you want to sort the key-value pairs.

Lets take the same example using LinkedHashMap and TreeMap:

Using LinkedHashMap

import java.util.*;
public class LinkedHashMapDemo
{
   public static void main(String args[])
   {
       LinkedHashMap<Integer, String> lhm= new LinkedHashMap<Integer, String>();
       lhm.put(10, "Chaitanya");
       lhm.put(1, "Ajeet");
       lhm.put(11, "Test");
       lhm.put(9, "Demo");
       lhm.put(3, "Anuj");
 
       // Get a set of the entries
       Set set = lhm.entrySet();
       // Get an iterator
       Iterator i = set.iterator();
       // Display elements
       while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
   }
}

Output:

10: Chaitanya
1: Ajeet
11: Test
9: Demo
3: Anuj

Voila!! We got the result in the insertion order.

What if we want to get the result sorted? Use TreeMap. Refer below example:

Use TreeMap

import java.util.*;
public class TreeMapDemo
{
   public static void main(String args[])
   {
      TreeMap<Integer, String> tm= new TreeMap<Integer, String>();
      tm.put(10, "Chaitanya");
      tm.put(1, "Ajeet");
      tm.put(11, "Test");
      tm.put(9, "Demo");
      tm.put(3, "Anuj");
      // Get a set of the entries
      Set set = tm.entrySet();
      // Get an iterator
      Iterator i = set.iterator();
      // Display elements
      while(i.hasNext()) {
        Map.Entry me = (Map.Entry)i.next();
        System.out.print(me.getKey() + ": ");
        System.out.println(me.getValue());
      }
  }
}

Output:

1: Ajeet
3: Anuj
9: Demo
10: Chaitanya
11: Test

As you can see, the output we got is sorted based on the keys.

Top Related Articles:

  1. HashMap in Java With Examples
  2. How to synchronize HashMap in Java with example
  3. How to loop LinkedList in Java
  4. JDBC(Java Database Connectivity) interview questions
  5. How to iterate TreeMap in reverse order in Java

Tags: Collections, Java-HashTable

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

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