How to initialize a Map in Java literally?

How can I initialize a Map in Java in a literal way?

Is there a way to directly initialize a Java HashMap like this:

Map<String, String> test = 
    new HashMap<String, String>{"test":"test","test":"test"};

What is the correct syntax for this? I haven’t found any reference to this style. I’m looking for the shortest and fastest way to initialize a map with “final” or “static” values that are known in advance and will not change. Is this possible in Java?

Ah, I’ve come across this question many times! If you’re looking for a way to java initialize map literally, Java doesn’t provide direct syntax like some other languages. But don’t worry—there are some great alternatives!

If you’re using Java 9 or later, the Map.of() method is your best bet. It allows you to create an immutable map concisely:

Map<String, String> test = Map.of(
    "test1", "value1", 
    "test2", "value2"
);

This is super clean and efficient, especially for small, fixed maps. Just remember—it creates an immutable map, so once initialized, you can’t modify it. Perfect for cases where you need constant values without worrying about accidental changes!

That’s a great approach if immutability is what you need! But if you need a mutable map (i.e., one you can modify later), or you’re on an older Java version, you’ll need a different method.

For that, you can use HashMap with put() like this:

Map<String, String> test = new HashMap<>();
test.put("test1", "value1");
test.put("test2", "value2");

This method gives you full flexibility since you can add, remove, or modify entries at any point. It’s a solid option when java initialize map needs to be dynamic rather than static.

Both approaches work well! But if you’re on Java 8 or higher and want a more streamlined, declarative way to initialize a map, try using Java Streams with Collectors.toMap().

Here’s how you can do it elegantly:

import java.util.Map;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toMap;

Map<String, String> test = Stream.of(new Object[][] {
     { "test1", "value1" },
     { "test2", "value2" }
}).collect(toMap(data -> (String) data[0], data -> (String) data[1]));

This is particularly useful when dealing with structured data that needs to be converted into a map dynamically. It keeps your initialization concise while ensuring flexibility.

At the end of the day, your choice depends on whether you need immutability (Map.of()), mutability (HashMap with put()), or a functional approach (Stream.of()). Each has its place in real-world Java development! :rocket: