Java Hashtable entrySet() Example

The entrySet() method of java.util.Hashtable class returns a Set view of the mappings 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<Map.Entry<K,V>> entrySet()

This method returns a Set view of the mappings 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.entrySet() method.

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

public class EntrySetMethodHashtableExample 
{
    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");
        
        //get the entrySet of hashtable1
        Set<Map.Entry<Integer,String>> set1 = hashtable1.entrySet();
        
        //Print the elements of hashtable1
        System.out.println("**Elements of hashtable1**");
        for (Map.Entry<Integer,String> me : set1) 
        {
            System.out.print(me.getKey() + ": ");
            System.out.println(me.getValue());
          }
    }
}

Output

**Elements of hashtable1**
5: Element5
4: Element4
3: Element3
2: Element2
1: Element1

Leave a Reply

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