Java Map keySet() example

In this guide, you will learn about the Map keySet() method in Java programming and how to use it with an example.

1. Map keySet() Method Overview

Definition:

The keySet() method of the Java Map interface is used to retrieve a set view of the keys contained in the map.

Syntax:

Set<K> keys = map.keySet();

Parameters:

- This method does not accept any parameters.

Key Points:

- The method returns a Set containing all the keys from the map.

- If you remove an item from the returned key set, the corresponding key-value pair is removed from the map.

- The key set does not support the add and addAll operations.

- Iterating over the key set is an efficient way to access every key-value pair in the map.

2. Map keySet() Method Example

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

public class MapKeySetExample {
    public static void main(String[] args) {
        Map<String, Integer> studentGrades = new HashMap<>();

        // Populate the map
        studentGrades.put("Alice", 90);
        studentGrades.put("Bob", 85);
        studentGrades.put("Charlie", 92);

        // Retrieve the key set
        Set<String> studentNames = studentGrades.keySet();

        // Print the keys
        System.out.println("Student names: " + studentNames);

        // Remove a key from the key set
        studentNames.remove("Bob");
        System.out.println("Map after removing 'Bob': " + studentGrades);
    }
}

Output:

Student names: [Alice, Bob, Charlie]
Map after removing 'Bob': {Alice=90, Charlie=92}

Explanation:

In this example:

1. We create a HashMap and populate it with student names as keys and their respective grades as values.

2. We then use the keySet() method to retrieve the set view of keys (student names).

3. After printing out the student names, we demonstrate the connection between the key set and the map by removing "Bob" from the key set. As a result, the key-value pair corresponding to "Bob" is also removed from the map.

The keySet() method provides a powerful way to iterate over keys and, in combination with the map, to access associated values. It's particularly useful in scenarios where one needs to process or transform all the keys in a map.

Related Map Interface methods

Java Map put() example
Java Map get() example
Java Map remove() example
Java Map containsKey() example
Java Map containsValue() example
Java Map keySet() example
Java Map values() example
Java Map entrySet() example

Comments