
Static Map of (K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) Static Map of (K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5)

Static Map of (K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) Static Map of (K k1, V v1, K k2, V v2, K k3, V v3) Please note that the Map interface has ten overloaded versions of the of() method. Map.of( "color", "black", "drink", "coffee") Code language: Java ( java ) The of() method of the Map interface accepts key-value pairs in the form of varargs and returns a new immutable HashMap containing the elements.Įxample of initializing Java HashMap inline using factory methods. Java 9 introduced factory methods to the Map interface that we can use to do inline initialization of Java HashMap instances. Introduction to HashMap in Java with Examples.
#INITIALIZE A HASHMAP JAVA HOW TO#

We have a separate tutorial on converting List to Map using Java Streams. Map map = new HashMap() Code language: Java ( java ) We can use an anonymous subclass to instantiate and initialize a Java HashMap in the same line. Creating a HashMap using Anonymous Subclass Map.put( "shape", "slim") Code language: Java ( java )Īlthough 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.Įxample of initializing a simple HashMap.
