Explain Codes LogoExplain Codes Logo

How to directly initialize a HashMap (in a literal way)?

java
map-initialization
java-9
immutable-maps
Anton ShumikhinbyAnton Shumikhin·Feb 16, 2025
TLDR

HashMap initialization in Java 9, use Map.of for small, immutable maps:

Map<String, Integer> map = Map.of("a", 1, "b", 2);

Serving fresh hot maps!

For Map.entry collections or larger maps:

Map<String, Integer> map = Map.ofEntries(Map.entry("a", 1), Map.entry("b", 2));

Who ordered the jumbo size?

In legacy scenarios, pre-Java 9, use double brace for mutable maps:

Map<String, Integer> map = new HashMap<>() {{ put("a", 1); put("b", 2); }};

Warranted to heat your JVM!

Go with Map.of/Map.ofEntries for immutable, fixed-size maps, or double brace initialization for mutable ones. Do consider Java version and immutability needs.

The advanced user manual

Making the undying, die: Making Immutable maps mutable

Create a mutable map from the ever so immutable Java 9 map:

Map<String, Integer> mutableMap = new HashMap<>(Map.of("a", 1, "b", 2));

Pop the corn and enjoy the immutability annihilation.

The One Ring: Singleton Map Initialization

For the special case of single-entry map initialization, pre-Java 9:

Map<String, Integer> singleEntryMap = Collections.singletonMap("a", 1);

One ring to rule them all, singleton map.

Here be dragons: Avoiding Memory Leaks

Coding with double brace initialization, beware, it generates an anonymous subclass and may lead to memory leaks:

Map<String, Integer> map = new HashMap<>() {{ put("a", 1); put("b", 2); }};

Better call garbage collector; memory leaks are in town.

Breaking the Null Barrier

Using Java 9's Map methods or Guava's ImmutableMap, the null values are forbidden. Beware the NullPointerException. Null is the nothingness we don't desire.

Mastering the complexities

Excavating Initializers: Static and Instance ones

Utilize static initializer blocks to make class-level map initialization:

static Map<String, Integer> staticMap; static { staticMap = new HashMap<>(); staticMap.put("a", 1); staticMap.put("b", 2); }

Baked fresh during class loading!

Instance initializers work within instance's constructors.

public MyClass() { map.put("a", 1); map.put("b", 2); }

Freshly baked instances are ready to serve.

Size does Matter: Dealing with Larger HashMaps

For large or dynamic maps, gravitate towards ImmutableMap.builder or Map.ofEntries(). Averts memory overhead:

ImmutableMap<String, Integer> largeMap = ImmutableMap.<String, Integer>builder() .put("a", 1) .put("b", 2) .build();

Opening doors to the 'Hogwarts' of maps.

Fortress of Solitude: Ensuring Data Security

Bolster your maps post-population with Collections.unmodifiableMap() or guarantee data integrity with Guava's ImmutableMap:

Map<String, Integer> securedMap = Collections.unmodifiableMap(new HashMap<>(Map.of("a", 1, "b", 2)));

Unmodifiable maps? Superman approves.

Polishing your map skills

Choosing the perfect attire: Initialization patterns

Initialization pattern selection is vital. Mind your requirements for mutability, size of map, and Java version compatibility.

Power of keys: Key Management

Treat keys like royalty; avoid accidental overwrites for data integrity. Unique keys and prudent hash functions are your pals.

The almost-there map literals

Java may not support map literals, but these methods come close. Clarity, maintainability, and readability - all packed in.