How to initialize a static map in Java

Overview

A map declared as static becomes a static map that we can access without instantiating the class.

We can initialize a static map in the following ways:

  • Static initialization block
  • The static method
  • The Map.ofEntries() method

Static initialization block

We can use static initialization blocks to initialize the static maps during class loading. The static blocks are executed after the execution of inline static initializers.

import java.util.HashMap;
import java.util.Map;
class Main
{
private static final Map<String, String> map;
static {
map = new HashMap<>();
map.put("one", "one");
map.put("two", "two");
}
public static void main(String[] args) {
System.out.println(map);
}
}

Explanation

  • Line 6: We define a static map.

  • Lines 7–11: We initialize the map as a hash map and insert sample data in it.

  • Line 14: We print the map.

Static method

We can move the static initialization code to a static method and use it to initialize a static map.

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
class Main
{
private static final Map<String, String> immutableMap = initializeMap();
private static Map<String, String> initializeMap() {
Map<String, String> map = new HashMap();
map.put("one", "one");
map.put("two", "two");
return Collections.unmodifiableMap(map);
}
public static void main(String[] args) {
System.out.println(immutableMap);
}
}

Explanation

  • Line 7: We initialize a static by invoking the static method initializeMap().

  • Lines 9–14: We create a hash map and add the sample data entries. The unmodifiableMap() method of the Collections class returns an unmodifiable view of the map.

  • Line 17: We print the map.

The Map.ofEntries() method

The Map.ofEntries() method creates a map with an arbitrary number of entries.

import java.util.Map;
import static java.util.Map.entry;
class Main {
private static final Map<String, String> map = Map.ofEntries(
entry("one", "one"),
entry("two", "two"),
entry("three", "three"),
entry("four", "four")
);
public static void main(String[] args) {
System.out.println(map);
}
}

Explanation

  • Lines 7–12: We define and initialize a static map using the map.entries() method.

  • Line 15: We print the map.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved