How to Initialize a HashMap in Java Without Losing Your Mind: A Complete Breakdown for Beginners
\n\nHave 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\nIn 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.
Why is simply "putting" elements such a pain?
\n\nImagine you need to create a HashMap with three key-value pairs. A typical beginner's code looks like this:
\n\nHashMap<String, Integer> map = new HashMap<>();\nmap.put("apple", 5);\nmap.put("banana", 3);\nmap.put("orange", 7);\n\nIt 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.
Method #1: Double Brace Initialization
\n\nThe most popular (and most controversial) way is double brace initialization. It looks like this:
\n\nHashMap<String, Integer> map = new HashMap<>() {{\n put("apple", 5);\n put("banana", 3);\n put("orange", 7);\n}};\n\nHow 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().
Pros:
\n- \n
- The code becomes more compact and readable. \n
- No need to write multiple lines with
put(). \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
Conclusion: it works, but it's better to use it only in test code or personal projects. Not recommended for production.
\n\nMethod #2: Guava (Google Library)
\n\nIf you use Google Guava (a very popular library), the problem is solved elegantly:
\n\nimport com.google.common.collect.ImmutableMap;\n\nMap<String, Integer> map = ImmutableMap.of(\n "apple", 5,\n "banana", 3,\n "orange", 7\n);\n\nFeatures:
\n- \n
- Creates an immutable map. \n
- The
of()method is overloaded for 0–5 pairs. For more, useImmutableMap.builder(). \n - Great for configurations and static data. \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\nMethod #3: Java 9+ — Map.of() and Map.ofEntries()
\n\nStarting with Java 9, the standard library introduced the M