Initializing HashMap in Java: The Secret of the "Literal" Way

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

How to Initialize a HashMap in Java Without Losing Your Mind: A Complete Breakdown for Beginners

\n\n

Have you ever written Java and felt like you needed to write a whole poem just to create a simple dictionary? Especially when you want to do it elegantly and compactly, like in Python or JavaScript. Sound familiar? On Stack Overflow, the question of how to initialize a HashMap in a literal way has thousands of views. And that's no coincidence.

\n\n

In this article, we'll break down all the legal ways to initialize a HashMap in Java, from the classic to the modern, with code examples and explanations for beginners. You'll learn how to fill a map in one line, when to use Map.of(), and why double brace initialization is a double-edged sword.

\n\n

Why is simply "putting" elements such a pain?

\n\n

Imagine you need to create a HashMap with three key-value pairs. A typical beginner's code looks like this:

\n\n
HashMap<String, Integer> map = new HashMap<>();\nmap.put("apple", 5);\nmap.put("banana", 3);\nmap.put("orange", 7);
\n\n

It seems fine, but when you have ten such maps, the code turns into a mess. You want conciseness, right? In Python, it's done in one line: dict = {"apple": 5, "banana": 3}. And in Java? Spoiler: there are several ways, and we'll cover them now.

\n\n

Method #1: Double Brace Initialization

\n\n

The most popular (and most controversial) way is double brace initialization. It looks like this:

\n\n
HashMap<String, Integer> map = new HashMap<>() {{\n    put("apple", 5);\n    put("banana", 3);\n    put("orange", 7);\n}};
\n\n

How does it work? The first curly braces create an anonymous inner class that inherits from HashMap. The second ones are an instance initializer block that runs when the object is created. Everything inside is calls to put().

\n\n

Pros:

\n
    \n
  • The code becomes more compact and readable.
  • \n
  • No need to write multiple lines with put().
  • \n
\n\n

Cons (and there are many):

\n
    \n
  • Performance: an anonymous class is created each time. This is extra work for the JVM.
  • \n
  • Memory: the anonymous class holds a reference to the outer class, which can cause memory leaks.
  • \n
  • Serialization: if you try to serialize such a map, problems may arise.
  • \n
  • Incompatibility: doesn't work with some frameworks (e.g., some versions of Gson).
  • \n
\n\n

Conclusion: it works, but it's better to use it only in test code or personal projects. Not recommended for production.

\n\n

Method #2: Guava (Google Library)

\n\n

If you use Google Guava (a very popular library), the problem is solved elegantly:

\n\n
import com.google.common.collect.ImmutableMap;\n\nMap<String, Integer> map = ImmutableMap.of(\n    "apple", 5,\n    "banana", 3,\n    "orange", 7\n);
\n\n

Features:

\n
    \n
  • Creates an immutable map.
  • \n
  • The of() method is overloaded for 0–5 pairs. For more, use ImmutableMap.builder().
  • \n
  • Great for configurations and static data.
  • \n
\n\n

Downside: you need to add an external dependency. If the project already uses Guava — great. If not — it might not be worth the trouble.

\n\n

Method #3: Java 9+ — Map.of() and Map.ofEntries()

\n\n

Starting with Java 9, the standard library introduced the M

Blogs

Book Recommendations