← All languages
Java method of the day
Random

Map.entry

Create an unmodifiable Map.Entry containing a key and value.

Description

The Map.entry() static method returns an unmodifiable Map.Entry containing the given key and value. It was introduced in Java 9 and is primarily used with Map.ofEntries() to create immutable maps with more than 10 entries.

Neither the key nor the value may be null. The returned entry does not support setValue() and will throw UnsupportedOperationException if attempted. The entry is value-based and callers should not rely on its identity.

This method provides a clean replacement for the verbose AbstractMap.SimpleImmutableEntry or custom entry implementations when you need to create map entries for use with Map.ofEntries() or other APIs that accept Map.Entry objects.

Arguments

NameDescriptionOptional
k The key of the entry. No
v The value of the entry. No

Example

Map<String, Integer> map = Map.ofEntries(
  Map.entry("a", 1),
  Map.entry("b", 2),
  Map.entry("c", 3)
);
map.get("b"); // 2

Reference