Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Map.Entry — a key-value pair

Map.Entry<K,V> represents one key-value pair. The getKey() method reads its key, while getValue() reads its value. An entry may be connected to a map or exist independently of one.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

Map.Entry<K, V> entry = Map.entry(key, value);
K keyResult = entry.getKey();
V valueResult = entry.getValue();

Map.Entry<K,V> is an interface nested in Map that represents one key-value pair, not an entire map. K specifies the key type, and V specifies the value type. Map.Entry.getKey() returns the key as K; Map.Entry.getValue() returns the value as V. Both methods take no arguments.

While iterating over map.entrySet(), you can read both components of each entry. Do not treat an entry obtained this way as a lasting copy: its behavior is undefined outside iteration or after modifying the map, except for a supported change through setValue() during iteration.

Map.entry(key, value) creates an unmodifiable entry independent of any map, as in the example. It rejects null keys and values; calling setValue() throws UnsupportedOperationException. In general, support for setValue() depends on the entry implementation.

Examples

import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map.Entry<String, Integer> entry = Map.entry("points", 42);
        String key = entry.getKey();
        Integer value = entry.getValue();
        System.out.println(key + " = " + value);
    }
}

Result

points = 42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources