Java Map entrySet() example

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

1. Map entrySet() Method Overview

Definition:

The entrySet() method of the Java Map interface returns a set view of the mappings contained in the map.

Syntax:

Set<Map.Entry<K, V>> entrySet = map.entrySet();

Parameters:

- This method does not take any parameters.

Key Points:

- The method returns a Set containing map entries, where each entry is a key-value pair represented by Map.Entry<K, V>.

- The set is backed by the map, meaning changes to the map are reflected in the set, and vice-versa.

- Removing an item from the returned set will remove the corresponding key-value pair from the map.

- The set supports entry removal, which also removes the corresponding key-value pair from the map, but it does not support the add or addAll operations.

- Iterating over the entrySet allows both the key and value of each mapping to be accessed simultaneously.

2. Map entrySet() Method Example

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

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

        // Populate the map
        countryCapital.put("USA", "Washington, D.C.");
        countryCapital.put("UK", "London");
        countryCapital.put("India", "New Delhi");

        // Retrieve the entry set
        Set<Map.Entry<String, String>> entries = countryCapital.entrySet();

        // Print each entry (key-value pair)
        for (Map.Entry<String, String> entry : entries) {
            System.out.println("Country: " + entry.getKey() + ", Capital: " + entry.getValue());
        }
    }
}

Output:

Country: USA, Capital: Washington, D.C.
Country: UK, Capital: London
Country: India, Capital: New Delhi

Explanation:

In the provided example:

1. We instantiated a HashMap and populated it with countries as keys and their respective capitals as values.

2. We then utilized the entrySet() method to fetch a set view of the map's entries.

3. We iterated over the set and printed each key-value pair.

The entrySet() method is especially beneficial when you need access to both the key and the value simultaneously, or when you want to perform operations that involve both the key and value within 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