Dung (Donny) Nguyen

Senior Software Engineer

Map.entry()

In Java, Map.entry() is a static method introduced in Java 9 as part of the Map interface. Its purpose is to create an immutable Map.Entry object, which represents a key-value pair. This method is useful for creating single entries without needing to create an entire Map instance.

Key Points:

  1. Immutable Entry: The Map.Entry created by Map.entry() is immutable, meaning its key and value cannot be modified after creation.
  2. Convenience: It provides a concise way to create key-value pairs, especially when working with collections or streams.
  3. Utility: It is often used in conjunction with methods like Map.of() or Map.ofEntries() to create small, immutable maps.

Syntax:

static <K, V> Map.Entry<K, V> entry(K key, V value)

Example Usage:

import java.util.Map;

public class Example {
    public static void main(String[] args) {
        // Create an immutable Map.Entry
        Map.Entry<String, Integer> entry = Map.entry("key", 123);

        // Access the key and value
        System.out.println("Key: " + entry.getKey());   // Output: Key: key
        System.out.println("Value: " + entry.getValue()); // Output: Value: 123

        // Use with Map.ofEntries to create a map
        Map<String, Integer> map = Map.ofEntries(
            Map.entry("one", 1),
            Map.entry("two", 2),
            Map.entry("three", 3)
        );

        System.out.println(map); // Output: {one=1, two=2, three=3}
    }
}

Use Cases:

Limitations:

In summary, Map.entry() is a utility method that simplifies the creation of immutable key-value pairs, making it easier to work with maps and collections in Java.