Java Map keySet() Method Tutorial

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

What is Java Map keySet() Method?

The Java Map keySet() method is used to get a “view” of the keys in a Map object.

Note: we say a “view” and not a copy! That means the object that returns as a result of calling this method is linked to the same keys that the target map object is linked to. So if one of them changed a key, the other will see the change.

Java keySet() Method Syntax:

Set<K> keySet()

keySet() Method Parameters:

The method does not take an argument.

keySet() Method Return Value:

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

keySet() Method Exceptions:

The method does not throw an exception.

Example: using Map keySet() method

import java.util.Map; 
import java.util.HashMap;
import java.util.Set;
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");

        Set<String> set = map.keySet();

        for (String s: set){
            System.out.println(s);
        }
    }
}

Output:

Elon

Barack

Omid

Jack

Lex
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies