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:
- Immutable Entry: The
Map.Entry
created byMap.entry()
is immutable, meaning its key and value cannot be modified after creation. - Convenience: It provides a concise way to create key-value pairs, especially when working with collections or streams.
- Utility: It is often used in conjunction with methods like
Map.of()
orMap.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:
- Creating Small Maps: When you need to create a small, fixed-size map with a few key-value pairs.
- Stream Operations: When working with streams and needing to create key-value pairs dynamically.
- Testing: For creating test data or mock entries in unit tests.
Limitations:
- The
Map.Entry
created byMap.entry()
is immutable, so you cannot modify its key or value after creation. - It is not intended for creating large maps, as it is more suited for small, fixed-size collections.
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.