Search code examples
javahashtableenumeration

How to sort hashtable/enumeration based on original input


I created a dictionary to output the keys of a hashtable.

import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;

public class Foo {
    public static void main (String [] args) {
         Dictionary<String, String> dict = new Hashtable<String, String>();
         dict.put("Emma", "Watson");
         dict.put("Tom", "Hanks");
         dict.put("Keanu", "Reeves");
    
         Enumeration<String> emu = dict.keys();
    
         while (emu.hasMoreElements()) {
              System.out.println(emu.nextElement());
         }
    }
}

Output :

Keanu
Emma
Tom

I want the output to be listed as the original order I put it in (Emma, Tom, Keanu) but it prints out this random order thats not even alphebetical. Please help me understand how and why this happens, and how to fix the problem


Solution

  • You should be using LinkedHashMap<>, which combines a hash map for quick access but also keeps the elements ordered by their insertion order. For example

    Map<String,String> dict = new LinkedHashMap<>();
    dict.put("Emma", "Watson");
    dict.put("Tom", "Hanks");
    dict.put("Keanu", "Reeves");
    
    for (String s : dict.keySet())
        System.out.println(s);
    

    This will output the keys in the order in which they were inserted into the map.

    BTW, Dictionary, Hashtable and related classes are very old and are superseded by Map and its implementations.