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.

import java.util.ArrayList; 
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
Hashtable ht = 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.Entry entry : ht.entrySet())
{
System.out.println(entry.getKey());
}

//create an arraylist with the keys retrieved from hashtable
List listcles = new ArrayList(ht.keySet());
//sort arraylist
Collections.sort(listcles);

System.out.println("After sorting:");
for(String key:listcles)
System.out.println(cle);
}
}
Output:

Before sorting:
b
a
e
d
c
After sorting:
a
b
c
d
e