beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to sort Hashtable in java

By Chaitanya Singh | Filed Under: Java Collections

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.

Leave a Reply Cancel reply

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

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap