How to directly initialize a HashMap in Java

May 30, 2017

To initialize a HashMap in Java you can use a below syntax:

However, there are also other options. You can find a detailed description below

1. Static initializer

In this option, we declare a static final map with String key and values. Then we make a static initializer and put needed things in it manually. Now, we are 100% sure that this set will be in our HashMap but if we would like to put some other objects in there in the future we can do so.

As a prove, we can print all the values  in main:

2. “Double-brace” syntax

This syntax (also introduced at the beginning of this post) is called double-brace. The first brace creates a new AnonymousInnerClass, the second declares and instance initializer block that is run when the anonymous inner class is instantiated. This kind of initializer is formally called an instance initializer. Sounds complicated, does it? If you want to use this option in your code you need to know how it works and beware of the invisible side effects.

The above code output is:


Click here to add a comment

Leave a comment:

Privacy Preference Center