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