How can I initialise a static Map?
To initialize a static Map
in Java, you can use the Map
interface's of
method, which was added in Java 9. The of
method creates an immutable Map
with a fixed set of key-value pairs.
For example, to create a static Map
that maps the strings "apple"
, "banana"
, and "cherry"
to their respective lengths, you can use the following code:
Map<String, Integer> map = Map.of(
"apple", 5,
"banana", 6,
"cherry", 6
);
This creates an immutable Map
with three key-value pairs.
You can also use the Map.ofEntries
method to create a Map
from a collection of Map.Entry
objects. For example:
Map<String, Integer> map = Map.ofEntries(
Map.entry("apple", 5),
Map.entry("banana", 6),
Map.entry("cherry", 6)
);
This creates an immutable Map
with the same key-value pairs as the previous example.
Note that the Map
objects created by the of
and ofEntries
methods are immutable, which means that you cannot modify the map after it is created. If you need a mutable map, you can use the HashMap class or one of the other mutable