Java HashMap keySet() Example

The keySet() method of java.util.HashMap class 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. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

Example

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

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class KeySetMethodHashMapExample 
{
    public static void main(String args[])
    {
        // create an empty HashMap
        HashMap<Integer,String>  hashMap1 = new HashMap<Integer,String>();
        
        // use put() method to put elements to the HashMap
        hashMap1.put(1,"Element1");
        hashMap1.put(2,"Element2");
        hashMap1.put(3,"Element3");
        hashMap1.put(4,"Element4");
        hashMap1.put(5,"Element5");
    
        // getting keyset value from map
        Set keyset=hashMap1.keySet();
 
        //Printing the values of the map
        System.out.println("Key set values are: " + keyset);
     } 
}

Output

 Key set values are: [1, 2, 3, 4, 5]

Leave a Reply

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