Explain Codes LogoExplain Codes Logo

How can I initialise a static Map?

java
static-map-initialization
java-collections
best-practices
Nikita BarsukovbyNikita Barsukov·Aug 28, 2024
TLDR

Here's how to initialize a static Map with Map.of for small immutable maps or a static block for a larger, mutable ones:

// Finite and beyond, these values can't be changed. Buzz Lightyear will be proud! private static final Map<String, Integer> IMMUTABLE_MAP = Map.of("One", 1, "Two", 2); // Mutable map... Like a baby, it changes a lot! private static final Map<String, Integer> MUTABLE_MAP = new HashMap<>(); static { MUTABLE_MAP.put("One", 1); MUTABLE_MAP.put("Two", 2); }

Thread safety and prevention of unintended modifications can be ensured by making your maps immutable:

// Immutable but certainly not impassable, Holmes! private static final Map<String, Integer> MY_CONSTANT_MAP; static { Map<String, Integer> temp = new HashMap<>(); temp.put("Uno", 1); temp.put("Dos", 2); MY_CONSTANT_MAP = Collections.unmodifiableMap(temp); }

For large data sets, Guava's ImmutableMap is your friend:

// Guava for larger tasks. Size does matter! import com.google.common.collect.ImmutableMap; private static final Map<String, Integer> MY_GUAVA_MAP = ImmutableMap.<String, Integer>builder() .put("One", 1) .put("Two", 2) .build();

And yes, in the world of standard coding practices, constants take the upper case route. Keep it in mind!

Advanced initialization techniques

Java Collections: A convenient toolkit

The Java Collections Framework gives us a neat little function you might not be using: Collections.unmodifiableMap(). This lets us create an unmodifiable map, a purist's joy:

// Collection's covert operation. Unmodifiable stealth mode ON! private static final Map<String, Integer> UNCHANGING_MAP = Collections.unmodifiableMap(new HashMap<>() {{ put("Alpha", 1); put("Beta", 2); }});

Shh...between you and me, double-brace initialization is frowned upon due to memory leaks and obscure coding. Let's keep it classy!

Static blocks: Use it with care

The good old static blocks are your knights in shining armor in matters of complex initialization or when the order matters, but dare not abuse their power!

  • For lazy loading or conditional initialization, bring in the cavalry - static holders or enumerations.

Guava: The all-in-one utility

Pledging allegiance to Java 8 and above? Get Guava 21+ for your utility needs. From maps to collections and more - it's the Swiss army knife of coding!

Immutable maps for safety & simplicity

Having immutable static maps beef up your application security by barricading your Map's contents from rogue changes. Consequently, choose the method that goes hand-in-hand with the degree of change your data experiences.

Applying best practices in static map initialization

When in the act of initializing a static map, fly the flag for code maintainability and named classes, as compared to the masked shadowy figure that are anonymous classes.