Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Declaration of Hashmap Class
3.
Parameters for Hashmap Class
3.1.
Load Factor
3.2.
Initial Capacity
4.
Initialization and Constructors for Hashmap
4.1.
Hashmap()
4.2.
HashMap(int initialCapacity)
4.3.
HashMap(int initialCapacity, float loadFactor)
4.4.
HashMap(Map map)
5.
Operations on Hashmap
5.1.
put()
5.2.
remove()
5.3.
get()
5.4.
clear()
5.5.
size()
5.6.
keySet()
5.7.
values()
5.8.
Example
6.
Frequently Asked Questions
7.
Key Takeaway
Last Updated: Mar 27, 2024

Introduction to Hash Map

Author Rhythm Jain
0 upvote
gp-icon
Data structures & algorithms (Beginner to Intermediate)
Free guided path
13 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

The HashMap class in Java implements the Map interface, which allows us to store key-value pairs with unique keys. The java.util package contains the HashMap class.

The data is stored as {Key, Value} pair, and you may retrieve them using a different form of the index (e.g., an Integer). A key (index) links one item to another (value). If we insert the duplicate key, it will overwrite the associated key's element.

Also read, Duck Number in Java and  Hashcode Method in Java

Declaration of Hashmap Class

We must import java.util to utilize this class and its methods. HashMap is a package or a superclass of HashMap. It implements the Map interface and inherits the AbstractMap class.

Syntax For Declaration of java.util.HashMap Class

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Parameters for Hashmap Class

HashMap<K,V>

It takes two parameters, K and V, while construction, namely as follows:

K: The type of keys maintained by this map

V: The type of mapped values

Load Factor

The Load Factor is a factor used internally by HashMap to decide whether the size of the Bucket array has to be raised. It is 0.75 by default. When the number of nodes in the HashMap exceeds 75% of its total capacity, HashMap expands the size of its bucket array. When HashMap's bucket array size has to be extended, its capacity is always doubled.

Initial Capacity

The Initial Capacity is effectively the number of buckets in the HashMap, set to 24 = 16 by default.

Also see,  Swap Function in Java

Initialization and Constructors for Hashmap

HashMap class provides four types of constructors as follow:

  1. HashMap()
  2. HashMap(int initialCapacity)
  3. HashMap(int initialCapacity, float load factor)
  4. HashMap(Map map)

Let us study each of them in-depth.

Hashmap()

It is the default constructor which creates a Hashmap with default properties.

Hashmap has a load factor of 0.75 and a capacity of 16.
Syntax

HashMap<K, V> hash = new HashMap<K, V>();

Example

import java.io.*;
import java.util.*;


class Main {


	public static void main(String args[])
	{
		HashMap<Integer, String> map1 = new HashMap<Integer, String>();


		map1.put(1, "coding");
		map1.put(2, "ninjas");


		System.out.println("Mappings of HashMap map1 are : "+ map1);


	}
}

 

Output

Mappings of HashMap map1 are : {1=coding, 2=ninjas}

 

You can also read about the Java Destructor

HashMap(int initialCapacity)

It creates an instance of HashMap with the specified initial capacity. The load factor is 0.75 by default.

Syntax

HashMap<K, V> hash = new HashMap<K, V>(int initialCapacity);

Example

import java.io.*;
import java.util.*;


class Main {

	
	public static void main(String args[])
	{
		HashMap<Integer, String> map1 = new HashMap<Integer, String>(2);


		map1.put(1, "coding");
		map1.put(2, "ninjas");


		System.out.println("Mappings of HashMap map1 are : "+ map1);


	}
}

Output

Mappings of HashMap map1 are : {1=coding, 2=ninjas}

HashMap(int initialCapacity, float loadFactor)

It creates a HashMap with the specified initial capacity and specified load factor.

Syntax

HashMap<K, V> hash = new HashMap<K, V>(int initialCapacity, int  loadFactor);

Example

import java.io.*;
import java.util.*;


class Main {


	public static void main(String args[])
	{
		HashMap<Integer, String> map1 = new HashMap<Integer, String>(2,0.5f);


		map1.put(1, "coding");
		map1.put(2, "ninjas");


		System.out.println("Mappings of HashMap map1 are : "+ map1);


	}
}

Output

Mappings of HashMap map1 are : {1=coding, 2=ninjas}

HashMap(Map map)

It is used to initialize the hashmap by using the elements of the given Map object “map.”

Syntax

HashMap<K, V> hash = new HashMap<K, V>(Map map);

Example

import java.io.*;
import java.util.*;


class Main {


	public static void main(String args[])
	{
		HashMap<Integer, String> map1 = new HashMap<Integer, String>();


		map1.put(1, "coding");
		map1.put(2, "ninjas");

		HashMap<Integer, String> map2= new HashMap<Integer, String>(map1);


		System.out.println("Mappings of HashMap map1 are : "+ map1);
		System.out.println("Mappings of HashMap map2 are : "+ map2);


	}
}

 

Output

Mappings of HashMap map1 are : {1=coding, 2=ninjas}
Mappings of HashMap map2 are : {1=coding, 2=ninjas}

Practice by yourself on online java compiler.

Operations on Hashmap

Although there are many operations on a HashMap today, we are going to discuss only the most commonly used functions

put()

put() method can add an element to the map. Also, we can change the element using the put() method.

remove()

We can use the remove() method to remove an element from the hashmap. This method takes the key as an input parameter and removes the mapping for a key from the given map if it exists.

get()

We can use the get() method to access an element from the hashmap for a corresponding key value.

clear()

We can use the clear() method to remove all the items from the Hashmap.

size()

we can use the size() method to get the total items present in the hashmap.

keySet()

We can use the keyset() method to iterate over the hashmap keys.

values()

We can use the values() method to iterate over the hashmap values.

Now let us demonstrate the above functions using an example

Example

import java.io.*;
import java.util.*;

class Main {

	public static void main(String args[])
	{
		HashMap<Integer, String> map1 = new HashMap<Integer, String>();

		//put()
		map1.put(1, "Ninja");
		map1.put(2, "Coder");
		map1.put(3, "Happy");
		map1.put(4, "Coding");
		System.out.println("Mappings of HashMap map1 are : "+ map1);
		
		//get()
		System.out.println("Value with key 2 is "+map1.get(2));
		
		//remove
		map1.remove(2);
		System.out.println("Mappings of HashMap map1 after removal are : "+ map1);
		
		
		//size
		System.out.println("Size of map1 are "+map1.size());

		//keyset()
		for (int i : map1.keySet()) {
            System.out.println(i);
        		}
        
            //values()
		for (String i : map1.values()) {
            System.out.println(i);
}
        
		//clear()
		map1.clear();
		System.out.println("Mappings of HashMap map1 after clear are : "+ map1);

	}
}

Output

Mappings of HashMap map1 are : {1=Ninja, 2=Coder, 3=Happy, 4=Coding}
Value with key 2 is Coder
Mappings of HashMap map1 after removal are: {1=Ninja, 3=Happy, 4=Coding}
Size of map1 are 3
1
3
4
Ninja
Happy
Coding
Mappings of HashMap map1 after clear are : {}

You can also check out Internal Working of HashMap

Frequently Asked Questions

  1. What is the Load factor in Hashmap?
    The Load Factor is a factor used internally by HashMap to decide whether the size of the Bucket array has to be raised. It is 0.75 by default. When the number of nodes in the HashMap exceeds 75% of its total capacity, HashMap expands the size of its bucket array. When HashMap's bucket array size has to be extended, its capacity is always doubled.
     
  2. What will happen if we store duplicate values in the HashMap?
    If we try to store a key already present in the HashMap, it will override the old value associated with the key and replace it with the new value.
     
  3. Can we store a null key in Hashmap?
    Yes, a null key can be stored in hashmap, but only one null key is allowed at a time.

Key Takeaway

Today, we learned about hashmap in Java, its implementation, and its functionality and methods. We also learned different approaches to declare and initialize Hashmap.

Recommended Readings:


If you wish to learn more about Java from experts, you can check out the Basics of Java with Data Structures and Algorithms course by coding ninjas.

Happy Coding!

Previous article
HashSet
Next article
Difference between HashMap and HashSet
Guided path
Free
gridgp-icon
Data structures & algorithms (Beginner to Intermediate)
13 chapters
109+ Problems
gp-badge
Earn badges and level up
Live masterclass