Java Hashtable keys() Example

The keys() method of java.util.Hashtable class will return an enumeration of the keys in this hashtable.

Signature

public Enumeration<K> keys() 

This method returns an enumeration of the keys in this hashtable.

Example

The following example shows the usage of java.util.Hashtable.keys() method.

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

public class KeysMethodHashtableExample 
{
    public static void main(String args[])
    {
        // create an empty Hashtable
        Hashtable<Integer,String>  hashtable1 = new Hashtable<Integer,String>();
        
        // use put() method to put elements to the Hashtable
        hashtable1.put(1,"Element1");
        hashtable1.put(2,"Element2");
        hashtable1.put(3,"Element3");
        hashtable1.put(4,"Element4");
        hashtable1.put(5,"Element5");
        
        //lets get all the keys of the hashtable
        Enumeration enumeration = hashtable1.keys();
        
        //Print all the keys of the hashtable
        System.out.println("**Keys of hashtable1**");
        while(enumeration.hasMoreElements())
        {
            System.out.println(enumeration.nextElement());
        }
    }
}

Output

**Keys of hashtable1**
5
4
3
2
1

Leave a Reply

Your email address will not be published. Required fields are marked *