Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

What is Double Brace Initialization in Java? Example Initializing HashMap and List with values in Java

Streams are also used to create mutable and immutable maps, but they degrade the performance. Another way to initialize a HashMap is to use the Map.of() function of the Java 9 version. Map.of() maps the keys and values passed as pairs, and then it returns an immutable HashMap. The HashMaps are key-value-based unordered, unsorted collections. We often use HashMaps in Java and put hard-coded values in it.

Since it is an immutable map, we cannot add more than one entry to it. This will result in the UnsupportedOperationException. The example uses Map.of and Map.ofEntriesto initialize hashmaps. Constructs a new HashMap with the same mappings as the specified Map. The HashMap is created with default load factor (0.75) and an initial capacity sufficient to hold the mappings in the specified Map.

Here what we do is during the creation of HashMap we assign the pairs using Map.of(). The following code gives a complete description of this type of initialization. Although this is a two-step operation, the HashMap we created is mutable; thus, we can add, remove, or modify elements. The most basic way of creating a HashMap instance and adding a few elements is to use a constructor to create an empty HashMap and then add elements one by one.

This will work since the static block always execute after inline static initializers. A return value of null does not necessarilyindicate that the map contains no mapping for the key; it’s also craft beer cellar columbia possible that the map explicitly maps the key to null. The containsKey operation may be used to distinguish these two cases. Intsize()Returns the number of key-value mappings in this map.

Today, we will cover various ways of creating and initializing Java HashMaps inline. Also, we will learn to create Immutable, Singleton, and Empty maps. A singleton map is an immutable map that stores a single key-value pair. We will use the Collections.singletonMap() method to initialize it.