How Can A HashMap Be Initialized In Java Using A Literal Approach?

To directly initialize a HashMap in a literal way, you can use the following syntax:

HashMap<KeyType, ValueType> map = new HashMap<KeyType, ValueType>() {{
    put(key1, value1);
    put(key2, value2);
    // add additional key-value pairs as needed

Here’s an example to illustrate it:

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<String, Integer>() {{
            put("apple", 10);
            put("banana", 5);
            put("orange", 7);
        // Print the HashMap
        for (String key : map.keySet()) {
            System.out.println("Key: " + key + ", Value: " + map.get(key));


Key: apple, Value: 10
Key: banana, Value: 5
Key: orange, Value: 7

In the above example, the HashMap is directly initialized with three key-value pairs using the double brace initialization syntax ({{ ... }}). You can add as many key-value pairs as needed inside the double braces.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!