How to Initialize HashMap in Java

HashMap is part of the java.util package, which extends the abstract class AbstractMap, which also provides an incomplete implementation of the map interface. It stores data in pairs (keys, values).
We can initialize a HashMap with a constructor in four different ways:

1.HashMap()

It is the default constructor with initial capacity 16 and load factor 0.75.

HashMap hs=new HashMap();

 

// Java program to demonstrate simple initialization
// of HashMap
import java.util.*;
public class GFG {
	public static void main(String args[])
	{
		HashMap<Integer, String> hm = new HashMap<Integer, String>();
		hm.put(1, "Ram");
		hm.put(2, "Shyam");
		hm.put(3, "Sita");
		System.out.println("Values " + hm);
	}
}

Output:

Values {1=Ram, 2=Shyam, 3=Sita}

2.HashMap(int initialCapacity)

Used to create an empty HashMap object with a specified initial capacity at a default load factor of 0.75.

HashMap hs=new HashMap(10);

 

// Java program to demonstrate initialization
// of HashMap with given capacity.
import java.util.*;
public class GFG {
	public static void main(String[] args)
	{
		HashMap<Integer, String> hm = new HashMap<Integer, String>(3);
		hm.put(1, "C");
		hm.put(2, "C++");
		hm.put(3, "Java");
		System.out.println("Values of hm" + hm);
	}
}

Output:

Values of hm{1=C, 2=C++, 3=Java}

3.HashMap(int initial capacity, float loadFactor)

Used to create an empty HashMap object with a specified initial capacity and load factor.

HashMap hs=new HashMap(10, 0.5);

 

// Java program to demonstrate initialization
// of HashMap with given capacity and load factor.
import java.util.*;
public class GFG {
	public static void main(String[] args)
	{
		HashMap<Integer, String> hm =
			new HashMap<Integer, String>(3, 0.5f);
		hm.put(1, "C");
		hm.put(2, "C++");
		hm.put(3, "Java");
		System.out.println("Values of hm" + hm);
	}
}

Output:

Values of hm{1=C, 2=C++, 3=Java}

4.HashMap(Map map)

It is used to initializes the hash map by using the elements of the given Map object map.

HashMap hs=new HashMap(map);

 

// Java program to demonstrate initialization
// of HashMap from another HashMap.
import java.util.*;
public class GFG {
	public static void main(String[] args)
	{
		HashMap<Integer, String> hm = new HashMap<Integer, String>();
		hm.put(1, "C");
		hm.put(2, "C++");
		hm.put(3, "Java");
		System.out.println("Values of hm" + hm);

		// Creating a new map from above map
		HashMap<Integer, String> language = new HashMap<Integer, String>(hm);

		System.out.println("Values of language " + language);
	}
}

Output:

Values of hm{1=C, 2=C++, 3=Java}
Values of language {1=C, 2=C++, 3=Java}

 

Submit Your Programming Assignment Details