How to initialize HashMap with values in Java? One liner

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 purpose than it's ok. This idiom internally uses the instance initializer of Anonymous inner class and cost 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 create 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 our program, you will find that we have a map called squares which are supposed to contain the number and it's 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

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 disadvantage of 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 Java application.


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 purpose but I don't advise you to use this technique in production. Instead, load data from database or config file.


Further Reading
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)
Java Generics and Collections - The Ultimate book on Java Collections (see here)


No comments:

Post a Comment