In Java 11 and later, you can use the Map.of
factory method to create an immutable Map
object with a fixed number of elements.
To create an immutable Map
using the Map.of
factory method, you can use the following syntax:
Map<KeyType, ValueType> map = Map.of(key1, value1, key2, value2, ...);
Here, KeyType
and ValueType
are the types of the keys and values in the Map
, key1
, key2
, etc. are the keys, and value1
, value2
, etc. are the values.
The Map.of
factory method returns a Map
object that contains the specified key-value pairs.
Here is an example of how you can use the Map.of
factory method to create an immutable Map
:
Map<String, Integer> map = Map.of("apple", 1, "banana", 2, "cherry", 3);
In this example, the map
object is an immutable Map
that contains the following key-value pairs: "apple" -> 1, "banana" -> 2, "cherry" -> 3.
It is important to note that the Map.of
factory method is available only in Java 11 and later, and it can be used to create Map
objects with up to 10 key-value pairs.
If you need to create a Map
object with more than 10 key-value pairs, or if you need to create a mutable Map
object, you can use the Map
interface's put
method or the HashMap
class's constructor.
For example, to create a mutable Map
object using the HashMap
class, you can use the following syntax:
Map<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); map.put("cherry", 3);