Open In App

Map keySet() Method in Java with Examples

Last Updated : 27 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

This method is used to return 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:

// Java Program Implementing Map
// keySet() Method
import java.util.*;

public class GfG 
{
    public static void main(String[] args)
    {

        // Initializing a Map of type HashMap
        Map<String, String> m = new HashMap<>();
      
          // Adding Elements in Map
          m.put("1" , "One"); 
        m.put("2" , "Two");

        // Printing Key Sets
        System.out.println(m.keySet());
    }
}

Output
[1, 2]

Syntax of Method

Set keySet()

Parameters: This method has no argument.

Returns: This method returns a set containing keys of the specified map.

Example for Map keySet()

Below is the code to show implementation of hashCode():

// Java code to show the implementation of
// keySet method in Map interface
import java.util.*;

public class GfG 
{
    public static void main(String[] args)
    {

        // Initializing a Map of type HashMap
        Map<Integer, String> m = new HashMap<>();
        Set<Integer> s = new HashSet<>();
        
          // Adding elements of HashMap
          m.put(1, "One");
        m.put(3, "Three");
        m.put(5, "Five");
        m.put(7, "Seven");
        m.put(9, "Nine");
        
          System.out.println(m);
        
        // Storing keys in Set 
          s = m.keySet();
        System.out.println(s);
    }
}

Output:

{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}
[1, 3, 5, 7, 9]

Reference: Oracle Docs


Next Article

Similar Reads

three90RightbarBannerImg