Initialize a HashMap in Java

In this module, we are going to discuss how to initialize a HashMap in Java Programming. HashMap is a Java Collections framework that provides HashTable for implementing the Map interface. HashMap implementation is similar to HashTable which is one of the data structures. Similar to HashTable which implements using <Key, Value> pairs HashMap also uses these <Key, Value> pairs.

Working With HashMap <Key, Value> Pairs Initialization

Here, keys are unique and we use them as indexes for accessing the values. These <Key, Value> pairs can be of any data type as Integer, String, Float, Long, Character, Double, etc. The below we can see the HashMap key matching to values like 32 integer value mapping to string object “Deepak”.

hashmap

The following is the syntax for creating HashMap:

HashMap<datatype,datatype> object=new HashMap<>()

Note: The data type can be Integer, String, Float, Long, Double, Character.

There are different ways for initializing HashMap the most common initialization is using put() which is adding <Key, Value> pairs to the map.

Using Put() method:

put() is a built-in function offered by HashMap. The following code gives a complete description of HashMap Initialization.

import java.io.*;
import java.util.*;
public class MyClass {
    public static void main(String args[]) {
      Map<Integer,String> map=new HashMap<>(); //HashMap creation
      map.put(32,"Deepak");
      map.put(9,"Seshu");                 //adding values to HashMap
      map.put(35,"Vishnu");
      map.put(55,"Nikilesh");
      System.out.println(map);
    }
}

Output:

{32=Deepak, 35=Vishnu, 55=Nikilesh, 9=Seshu}

Using Direct Initialization:

Here what we do is during the creation of HashMap we assign the <Key, Value> pairs using Map.of(). The following code gives a complete description of this type of initialization.

import java.io.*;
import java.util.*;
public class MyClass {
    public static void main(String args[]) {
Map<Integer,String> map=Map.of(32,"Deepak",55,"Nikilesh",9,"Seshu");
      System.out.println(map);
    }
}

Output:

{9=Seshu, 32=Deepak, 55=Nikilesh}

Note:

it has limitations to the number of <Key, Value> pairs.

Using SubClass for Initialization:

Here we initialize HashMap using the subclass which is created after defining the object of HashMap. The following is the syntax for creation.

Map<datatype,datatype> map=new HashMap<>(){{    put(key,value);   .....}};

The following code gives a complete description of this type of initialization.

import java.io.*;
import java.util.*;
public class MyClass {
    public static void main(String args[]) {
Map<Integer,String> map=new HashMap<>(){{
    put(32,"Deepak");
    put(9,"Seshu");
    put(55,"Nikilesh");
}};
        
      System.out.println(map);
    }
}

Output:

{32=Deepak, 55=Nikilesh, 9=Seshu}

Leave a Reply

Your email address will not be published. Required fields are marked *