How would you initialise a static Map
in Java?
Method one: static initialiser
Method two: instance initialiser (anonymous subclass)
or
some other m
JEP 269 provides some convenience factory methods for Collections API. This factory methods are not in current Java version, which is 8, but are planned for Java 9 release.
For Map
there are two factory methods: of
and ofEntries
. Using of
, you can pass alternating key/value pairs. For example, in order to create a Map
like {age: 27, major: cs}
:
Map info = Map.of("age", 27, "major", "cs");
Currently there are ten overloaded versions for of
, so you can create a map containing ten key/value pairs. If you don't like this limitation or alternating key/values, you can use ofEntries
:
Map info = Map.ofEntries(
Map.entry("age", 27),
Map.entry("major", "cs")
);
Both of
and ofEntries
will return an immutable Map
, so you can't change their elements after construction. You can try out these features using JDK 9 Early Access.