Java Map entrySet() Method Tutorial

In this section, we will learn what the Map entrySet() method is and how to use it in Java.

What is Java Map entrySet() Method?

The Java Map entrySet() method is used to get a Set view of a map object.

Note: we say a “view” and not a copy! This is because both Set and the target Map object are linked to the same entries (keys and values) and so each of these objects can change the elements and the other will see the changes.

Java entrySet() Method Syntax:

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

entrySet() Method Parameters:

The method does not take an argument.

entrySet() Method Return Value:

The return value of this method is an object of type Set.

Note: please check the Map.Entry section if you’re not familiar with this interface.

entrySet() Method Exceptions:

The method does not throw an exception.

Example: using Map entrySet() method

import java.util.Map; 
import java.util.HashMap;
class Main{
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>();
        map.put("Omid","Dehghan");
        map.put("Jack","Bauer");
        map.put("Barack","Obama");
        map.put("Elon","Musk");
        map.put("Lex","Fridman");

        System.out.println(map.entrySet());
    }
}

Output:

[Elon=Musk, Barack=Obama, Omid=Dehghan, Jack=Bauer, Lex=Fridman]
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies