How to Sort Hashtable in Java?
Last Updated :
04 Jan, 2021
Given a Hashtable, the task is to sort this Hashtable. Hashtable is a data structure that stores data in key-value format. The stored data is neither in sorted order nor preserves the insertion order.
Example
Java
import java.io.*;
import java.util.*;
public class SortHashtable {
public static void main(String[] args)
{
Hashtable<Integer, String> ht
= new Hashtable<Integer, String>();
ht.put( 2 , "mango" );
ht.put( 3 , "orange" );
ht.put( 1 , "apple" );
Set<Integer> keys = ht.keySet();
Iterator<Integer> itr = keys.iterator();
while (itr.hasNext()) {
Integer i = itr.next();
System.out.println(i + " " + ht.get(i));
}
}
}
|
Output
3 orange
2 mango
1 apple
The Hashtable mappings can be sorted using the following two ways:
- Using TreeMap
- Using LinkedHashMap
Examples:
Input: Hashtable: {2: “mango”, 1: “apple”, 3: “orange”}
Output: 1 apple
2 mango
3 orange
Input: Hashtable: {3: “three”, 2: “second”, 1:”first”}
Output: 1 first
2 second
3 third
Approach 1:
TreeMap stores the data in sorted order. We can use the TreeMap constructor and convert the Hashtable object into a TreeMap object. Now the resultant TreeMap object is in sorted order.
Syntax:
TreeMap<K, V> tm = new TreeMap<K, V>(Map m);
Parameters: m is the Hashtable in our program.
Example
Java
import java.io.*;
import java.util.*;
public class SortHashtable {
public static void main(String[] args)
{
Hashtable<Integer, String> ht
= new Hashtable<Integer, String>();
ht.put( 2 , "mango" );
ht.put( 3 , "orange" );
ht.put( 1 , "apple" );
TreeMap<Integer, String> tm
= new TreeMap<Integer, String>(ht);
Set<Integer> keys = tm.keySet();
Iterator<Integer> itr = keys.iterator();
while (itr.hasNext()) {
Integer i = itr.next();
System.out.println(i + " " + tm.get(i));
}
}
}
|
Output
1 apple
2 mango
3 orange
Approach 2:
LinkedHashMap stores the data in the order in which it is inserted. As when the data comes insert it into LinkedHashMap which has a property to preserve the insertion order.
Syntax:
LinkedHashMap<K, V> lhm = new LinkedHashMap<K, V>();
Example
Java
import java.io.*;
import java.util.*;
public class SortHashTable {
public static void main(String[] args)
{
LinkedHashMap<Integer, String> lhm
= new LinkedHashMap<Integer, String>();
lhm.put( 2 , "mango" );
lhm.put( 3 , "orange" );
lhm.put( 1 , "apple" );
Set<Integer> keys = lhm.keySet();
Iterator<Integer> itr = keys.iterator();
while (itr.hasNext()) {
Integer i = itr.next();
System.out.println(i + " " + lhm.get(i));
}
}
}
|
Output
2 mango
3 orange
1 apple
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...