Initialize a static map in Java
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.HashMap; import java.util.Map; class Main { private static final Map<Integer, String> map; static { map = new HashMap<>(); map.put(1, "one"); map.put(2, "two"); } public static void main(String[] args) { System.out.println(map); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.Collections; import java.util.HashMap; import java.util.Map; class Main { private static final Map<Integer, String> immutableMap; static { Map<Integer, String> mutableMap = new HashMap<>(); mutableMap.put(1, "one"); mutableMap.put(2, "two"); immutableMap = Collections.unmodifiableMap(mutableMap); } public static void main(String[] args) { System.out.println(immutableMap); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import java.util.HashMap; import java.util.Map; class Builder<K, V> { private final Map<K, V> map; public Builder(Map<K, V> map) { this.map = map; } public Builder<K, V> put(K k, V v) { map.put(k, v); return this; } } class Main { private static final Map<Integer, String> map = new HashMap<>(); static { new Builder<>(map) .put(1, "one") .put(2, "two") .put(3, "three") .put(4, "four") .put(5, "five"); } public static void main(String[] args) { System.out.println(map); } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.Collections; import java.util.HashMap; import java.util.Map; class Main { private static final Map<Integer, String> immutableMap = initializeHashMap(); private static Map<Integer, String> initializeHashMap() { Map<Integer, String> map = new HashMap(); map.put(1, "one"); map.put(2, "two"); return Collections.unmodifiableMap(map); } public static void main(String[] args) { System.out.println(immutableMap); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.Arrays; import java.util.Map; import java.util.stream.Collectors; class Main { private static final Map<String, String> map = Arrays.stream(new String[][]{ {"1", "one"}, {"2", "two"} }).collect(Collectors.toMap(keyMapper -> keyMapper[0], valueMapper -> valueMapper[1])); public static void main(String[] args) { System.out.println(map); } } |
To initialize a map with different types for key and value, for instance Map<Integer, String>, we can do something like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.Arrays; import java.util.Map; import java.util.stream.Collectors; class Main { private static final Map<Integer, String> map = Arrays.stream(new Object[][]{ {1, "one"}, {2, "two"} }).collect(Collectors.toMap(keyMapper -> (Integer) keyMapper[0], valueMapper ->(String) valueMapper[1])); public static void main(String[] args) { System.out.println(map); } } |
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>:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.AbstractMap.SimpleEntry; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; class Main { private static final Map<Integer, String> map = Stream.of( new SimpleEntry<>(1, "one"), new SimpleEntry<>(2, "two")) .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue)); public static void main(String[] args) { System.out.println(map); } } |
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,
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.Map; class Main { private static final Map<Integer, String> map = Map.of( 1, "one", 2, "two" ); public static void main(String[] args) { System.out.println(map); } } |
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).
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.Map; import static java.util.Map.entry; class Main { private static final Map<Integer, String> map = Map.ofEntries( entry(1, "one"), entry(2, "two"), entry(3, "three"), entry(4, "four"), entry(5, "five"), entry(6, "six"), entry(7, "seven"), entry(8, "eight"), entry(9, "nine"), entry(10, "ten") ); public static void main(String[] args) { System.out.println(map); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.HashMap; import java.util.Map; class Main { private static final Map<Integer, String> map = new HashMap<Integer, String>() {{ put(1, "one"); put(2, "two"); }}; public static void main(String[] args) { System.out.println(map); } } |
That’s all about initializing a static map in Java.
Also Read:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)