Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Map key-set view: `Map.keySet()`

`Map.keySet()` returns a set of keys backed by the map. Changes to the map appear in the view, and removing a key through the view removes its mapping if removal is supported.

Version: Java SE 21

Syntax

java.util.Map<K, V>: Set<K> keySet();

Map.keySet() returns a Set<K> containing the map’s keys. It is a view, not a snapshot: a key added to the map appears even in a view you obtained earlier.

If the view supports removal, keys.remove(key) removes the entire key–value mapping from the map. The view does not support adding keys with add or addAll.

HashMap does not guarantee iteration order. To display the keys in a predictable order, copy them into a list and sort the copy.

Examples

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MapKeySetDemo {
    public static void main(String[] args) {
        Map<String, Integer> stock = new HashMap<>();
        stock.put("pear", 5);
        stock.put("apple", 4);
        stock.put("plum", 1);

        Set<String> keys = stock.keySet();
        stock.put("lime", 2);
        System.out.println("Before: " + keys.size());

        keys.remove("lime");
        keys.remove("plum");
        System.out.println("After: " + stock.size());

        List<String> displayKeys = new ArrayList<>(keys);
        Collections.sort(displayKeys);
        System.out.println("Keys: " + displayKeys);
    }
}

Result

Before: 4
After: 2
Keys: [apple, pear]

The code adds `lime` after obtaining the view, but `keys.size()` still counts it. Removing `lime` and `plum` through the view leaves two mappings in the map. Sorting a copy of the keys produces `[apple, pear]`.

Related lessons

  • Java · Lesson 45 · Advanced · Version: 2

Sources