This post will discuss various methods to initialize a static map in Java.

1. Using Static Initialization Block

In Java, we can use a static block (or static initialization block) to initialize the static fields during class loading. This will work since the static block always execute after inline static initializers.

Download  Run Code

 
A good practice is to ensure that the static map is not modified later at any point. We can do this by creating an immutable map. The idea is to wrap the mutable map with Collections.unmodifiableMaput() and creating an unmodifiable “read-only” view of the original map.

Download  Run Code

 
To create a map with several entries, it’s better to create a type-safe Builder class, as shown below. Then we can use Builder’s put() method, which takes key-value pairs instead of a map. put() associates key with value in the built map.

Download  Run Code

2. Using Static Method

We can make the creation of the map more explicit by using a static method for initializing it, as shown below:

Download  Run Code

3. Using Java 8

We can use Java 8 Stream to construct static maps by obtaining stream from static factory methods like Stream.of() or Arrays.stream() and accumulating the input elements into a new map using collectors.

Download  Run Code

 
To initialize a map with different types for key and value, for instance Map<Integer, String>, we can do something like:

Download  Run Code

 
Another approach that can easily accommodate different types for key and value involves creating a stream of map entries. There are two implementations of Map.Entry<K,V> interface in java.util.AbstractMap: SimpleEntry<K,V> and SimpleImmutableEntry<K,V>. The following example demonstrates the use of AbstractMap.SimpleEntry<K,V>:

Download  Run Code

4. Using Java 9

Java 9 made it very convenient to create instances of the map by providing static factory method of() on the Map interface, which can create a compact, unmodifiable instance of Map. For example,

Download  Run Code

 
Note that Map.of() can support up to 10 key-value pairs. There is a no var-args overload of Map.of(), which can handle any number of mappings. To create a map with an arbitrary number of entries, we can use Map.ofEntries(Map.Entry<K,V>…).It includes varargs overloads, so there is no fixed limit on the map size. This approach requires each key-value pair to be boxed. For boxing keys and values, we can use Map.Entry<K,V> entry(K k, V v).

Download  Run Code

5. Using Double Brace Initialization

Another alternative is to use “Double Brace Initialization”. This creates an anonymous inner class with an instance initializer in it. Note that the use of Double Brace Initialization is discouraged in Java.

Download  Run Code

That’s all about initializing a static map in Java.

 
Also Read:

Initialize Map in Java using Guava Library

Initialize Map in Java using Apache Commons Collections