A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/map-keyset-method-in-java-with-examples/ below:

Map keySet() Method in Java with Examples

Map keySet() Method in Java with Examples

Last Updated : 27 Nov, 2024

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
// 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());
    }
}
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
// 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



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4