Sort Keys in a HashTable in Java
You can't sort a HashTable with its keys, but you can rescue the ArrayList collection that is caught in the argument of the method Collections.sort().
In this example, we are copying the keys from HashTable to an ArrayList. Keys are obtained with keySet(), then call Collections.sort() which takes as an argument the newly created ArrayList which contains our keys.
In this example, we are copying the keys from HashTable to an ArrayList. Keys are obtained with keySet(), then call Collections.sort() which takes as an argument the newly created ArrayList which contains our keys.
import java.util.ArrayList;Output:
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
public class TriTreeMap {
public static void main(String[] args) {
//create a hashtable
Hashtableht = new Hashtable ();
//add key-value pairs
ht.put("d", "fourth");
ht.put("a", "first");
ht.put("c", "third");
ht.put("e", "fifth");
ht.put("b", "second");
System.out.println("Before sorting:");
for (Map.Entryentry : ht.entrySet())
{
System.out.println(entry.getKey());
}
//create an arraylist with the keys retrieved from hashtable
Listlistcles = new ArrayList (ht.keySet());
//sort arraylist
Collections.sort(listcles);
System.out.println("After sorting:");
for(String key:listcles)
System.out.println(cle);
}
}
Before sorting:
b
a
e
d
c
After sorting:
a
b
c
d
e