Java Hashtable keySet() Method Example

The keySet() method of java.util.Hashtable class will returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa

Signature

public Set<K> keySet()

This method returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa

Example

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

package com.javainterviewpoint;

import java.util.Hashtable;
import java.util.Set;

public class KeySetMethodHashtableExample
{
    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");
        
        Set<Integer> set = hashtable1.keySet();
        System.out.println("**Keyset of \"hashtable1\"**");
        for(Integer val : set)
        {
            System.out.println(val);
        }
    }
}

Output

**Keyset of "hashtable1"**
5
4
3
2
1

Leave a Reply

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