How to initialize HashMap with values in Java? Example

There is often a situation where you would like to create a HashMap with some pre-defined mapping, but unfortunately, Java doesn't provide map literals like Groovy or Scala to create the map with values in the same line. If you remember, we have faced the same issue with other Collection classes as well e.g. ArrayList, Vector, or LinkedList. But ArrayList is lucky because you can still use the Arrays.asList() method to create and initialize the ArrayList in just one line as shown here. But, how do you initialize the HashMap with values in Java? 

There is no such method like Arrays.asMap() or Collections.asMap(), and this is not just the question about HashMap but also about Hashtable, LinkedHashMap and ConcurrentHashMap.

Well, there is an idiom called double brace initialization, which you can use to initialize the HashMap at the time of declaration. I'll show you how to use that double brace initialization to create HashMap with values in this article with a simple example.



How to create HashMap with values in Java

As I told you can use the Double brace initialization to create HashMap with values. Btw, this is not a very good pattern, in fact, it is considered as an anti-pattern in Java, but if you are doing this just for utility or testing purposes then it's ok. 

This idiom internally uses the instance initializer of Anonymous inner class and costs an extra class every time you use it, but you can use it to initialize both static and non-static HashMap as shown in our example. 

Another drawback of this idiom is that it holds a hidden reference of enclosing class which may cause the memory leak in Java application.

How to create HashMap with values in Java


The good thing about this idiom is that It requires less code i.e. you don't need to create HashMap without values and then subsequently call the put() method, but you can both create and initialize the Map in the same line.

You can also use double brace initialization with LinkedHashMap, TreeMap, ConcurrentHashMap, and Hashtable, in fact, with any Map implementation e.g. EnumMap and WeakHashMAp.




Java Program to initialize HashMap with values

Here is our sample Java program to create and initialize the HashMap in the same line.  In this example, we have used the double brace initialization idiom to initialize both static and non-static HashMap

If you look at our program, you will find that we have a map called squares which are supposed to contain the number and its square. 

This HashMap is initialized in the static initializer block.  Then, we have another Integer to String Map called IdToName, this is also created and initialized at the same line.

import java.util.HashMap;
import java.util.Map;

/**
 * Java Program to show you can initialize a HashMap wit values in one line.
 * You can use this technique to initialize static Maps in Java.
 *
 * @author WINDOWS 8
 */
public class HashMapWithValues {

    private static final Map<Integer, Integer> squares;
    
    static{
      squares =   new HashMap<Integer, Integer>() {{
            put(2, 4);
            put(3, 9);
            put(4, 16);
        }};
    }
    
    public static void main(String args[]) {

        Map<Integer, String> idToName = new HashMap<Integer, String>() {{
            put(101, "John");
            put(102, "John");
            put(103, "John");
        }};
     
        System.out.println(idToName);
        System.out.println(squares);
    }

}

Output :
{101=John, 102=John, 103=John}
{2=4, 3=9, 4=16}


Pros and Cons of Initializing HashMap with Values

Though this technique, double brace initialization looks great when you first learn about it, it has its shares of problems as discussed in the second paragraph. Let's see the advantages and disadvantages of the double brace initialization pattern for quick reference:

Advantages:
1) less line of code
2) Instantiation and initialization in the same expression.

Disadvantages:
1) Not very readable. This idiom internally uses the Anonymous inner class, which is not clear by just looking at it.
2) It creates a new class every time you use this pattern to initialize HashMap.
3) It holds a hidden reference of the enclosing instance, which may cause the memory leak in the Java application.

Update: Map.of() method to create a Map with key and values in Java

This article was written quite a few years ago and there are new developments with JDK 9 introducing Immutable collections. So from JDK 9 onwards you can also use Map.of(key, value) method to create a Map with value in Java. 

There is no guarantee that it will be HashMap but it will serve the purpose. In fact if you need a Map with values, I strongly recommend to use that method 

That's all about how to initialize HashMap in Java in one line. You can use the double brace initialization pattern to create HashMap with values but beware of all the disadvantages associated with this idiom. It's good for testing and demo purposes but I don't advise you to use this technique in production. Instead, load data from the database or config file.


Other Java Collection tutorials you may like
  • The difference between HashMap and LinkedHashMap in Java? (answer)
  • The best way to iterate over HashMap in Java? (answer)
  • How to sort the HashMap on keys and values in Java? (solution)
  • 3 ways to loop over a Map in Java? (example)
  • The difference between HashMap and ConcurrentHashMap in Java? (answer)
Thanks for reading this article so far. If you found this HashMap initialization with values Example useful then please share them with your friend circle. 

And now is the quiz time, What is difference between HashMap, TreeMap, and LinkedHashMap in Java? Which one of these will you use if you need to keep the keys in sorted order and in the order they are inserted in?

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.