The reason HashMap is called HashMap in Java is that it uses a hash function to convert the key into a hash and store it.

There is a data structure called “HashMap” in Java, which stores data in Key-Value pair format. HashMap is a part of the Java Collection Framework and provides the convenience of storing data via the functionality of the HashTable Data structure.

HashMap can be used easily in a program by importing “Java.util.HashMap” class. Soon we will see the initialization, in-built method, traversing, and other stuff related to HashMap, But before that let us see the difference between HashMap and HashTable first.

HashMap vs HashTable in Java

Both HashMap and HashTable store the data in Key-Value format. When we put a key into these data structures the key is converted into a code called a Hashcode using the Hash function, Which gives unique or duplicate code for each unique Key and the same for the same Key.

HashMap vs HashTable in Java
HashMap vs HashTable in Java

This process is known as Hashing. This code is used as a location number where the value belonging to the key is present.

In this way both of the data structures used the same concept but has some differences as well, Which are listed below :

  1. HashMap is non-synchronized, not thread-safe, and can’t be shared between many threads On the other hand, HashTable is synchronized, thread-safe, and can be shared with many threads as well.
  2. We can use at most one null Key and multiple null values in HashMap, But the same thing is not possible with HashTable. We can’t store any null key and value in HashTable.
  3. HashMap has better functionality and convenience as compared to HashTable. Therefore, Generally, HashMap is preferred over HashTable.

So far till now, We have known about what type of Data is stored in HashMap and HashTable along with the differences between them. Now, let’s move towards the initialization, use, and some in-built methods of HashMap.

How to Initialize HashMap in Java

For initializing HashMap, First, we have to import the HashMap class using “java.util.*” package.

we use HashMap<K, V> map = new HashMap<>(); for initializing a HashMap, Where K and V are representing the data type of Key and Value respectively.

We can change the data type of Key or value or both as per our application. Below the code is given as a demonstration for the initialization of HashMap.

Code :

            package newPackage;
			import java.util.HashMap;
			import java.io.*;
			import java.lang.*;
			
			class BeeTechnical
			{
			    public static void main(String args[])
			    {
			    	HashMap<Integer, Integer> map = new HashMap<>();
			    	System.out.println("Initialized map is : "+map);
			    }  	
			}

Output :

The output of initialized HashMap in Java
The output of initialized HashMap in Java

In the output of the code, we can see that map is successfully initialized, But shows opening and closing curly braces only and noting in between them, Which is because there is no Key-Value pair present in the map currently.

Therefore, Map in the output is empty. We will see a map containing Key-Value pairs soon.

In-Built functions of HashMap

Let’s look at each built-in function that HashMap has to execute basic operations with an example.

HashMap Put Method

Code :

            package newPackage;
			import java.util.HashMap;
			import java.io.*;
			import java.lang.*;
			
			class BeeTechnical
			{
			    public static void main(String args[])
			    {
			    	HashMap<Integer, Integer> map = new HashMap<>();
			    	map.put(1, 1);
			    	map.put(2, 3);
			    	map.put(4, 6);
			    	//putting key = 4 and value = 6 by above line of code
			    	map.put(4, 3);
			    	//putting key = 4 and value = 3 by above line of code
			    	map.put(7, 7);
			    	System.out.println("Initialized map is : "+map);
			    }  	
			}

Output :

Add Elements to HashMap using the Put Method in Java
Add Elements to HashMap using the Put Method in Java

In the output, we can clearly see that map has initialized. It should be noted that a map can contain only unique keys.

In the code above, you can see two comments. We are putting key 4 twice one by one using the put() method as the key must be unique in the map.

When we try to put the same key again, Which is already present in the map, Then the old value related to the key is replaced by a new value.

Therefore, the previous value 6 related to key 4 is replaced by new value 3 and we can see the output of the map containing new value 3 replacing old value 6 related to the key.

How to use Get Method in HashMap?

As a map contains only unique keys, Therefore it is obvious that we can easily find a value if we know the key.

get(E e) method does the same thing for us, it takes an element e of E data type as an argument and returns the value related to that key, If the map contains that key else returns null.

Code :

            package newPackage;
			import java.util.HashMap;
			import java.io.*;
			import java.lang.*;
			
			class BeeTechnical
			{
			    public static void main(String args[])
			    {
			    	HashMap<Character, Integer> map = new HashMap<>();
			    	map.put('b', 5);
			    	map.put('e', 3);
			    	map.put('d', 6);
			        System.out.println("Initialized map is : "+map);
			    	System.out.println("Value related to Key d is : "+map.get('d'));
			    	System.out.println("Value related to Key a is : "+map.get('a'));
			    }  	
			}

Output :

Find the value using the key in HashMap
Find the value using the key in HashMap

In the code above, we initialized a map of <Character, Integer> data type as Key and value respectively.

It can be seen that the map contains value 6, Which is related to the character key ‘d’. Therefore, map.get(‘d’) is returning 6, While the map doesn’t contain character a, Therefore, it is returning null as output.

Remove the HashMap elements using Remove Method

Any <Key, Value> pair which resides in the map can be removed from it easily using the remove(Key) or remove(Key, Value) method.

The remove (key) method removes the key if the key is present in the map same remove(key, value) removes the <Key,Value> pair if both key and value exist in the map.

Code :

            package newPackage;
			import java.util.HashMap;
			import java.io.*;
			import java.lang.*;
			
			class BeeTechnical
			{
			    public static void main(String args[])
			    {
			    	HashMap<Character, Integer> map = new HashMap<>();
			    	map.put('b', 5);
			    	map.put('e', 3);
			    	map.put('d', 6);
			        System.out.println("Initially map is : "+map);
			        map.remove('e');
			        //Removing key e in above line
			    	System.out.println("Map after removing key e is  : "+map);
			    	//Trying to Remove key b and value 6 in above line
			    	map.remove('b',6);
			    	System.out.println("Map after removing key b and value 6 is  : "+map);
			    	//Trying to Remove key b and value 5 in above line
			    	map.remove('b',5);
			    	System.out.println("Map after removing key b and value 5 is  : "+map);
			    }  	
			}

Output :

Remove elements using the remove method
Remove elements using the remove method

In the code above, At first comment we are trying to remove key ‘e’ from the map using map.remove(‘e’) in the code,

A map contains the key ‘e’.Therefore, Key ‘e’ is removed from the map.

In the second comment, We are removing key ‘e’ and Value 6 from the map by using the map.remove(‘b’, 6), But it should be noted that, Map contains the value 5 corresponding to the key ‘b’.

Therefore, map.remove(‘b’, 6) will not remove that <b, 5> pair, Which is successfully removed later after using a line of code map.remove(b, 5) at the third comment.

Formally, for removing <Key, Value> pair using remove(Key) method the Key must be present in the map, and for removing a pair using remove(Key, Value) method the Key and Value passed as arguments in the method must be present in the map.

Find the Size of the HashMap using the inbuilt Method

size() function simply returns the size of the map or we can say the number of entries or pairs in the map.

Code :

            package newPackage;
			import java.util.HashMap;
			import java.io.*;
			import java.lang.*;
			
			class BeeTechnical
			{
			    public static void main(String args[])
			    {
			    	HashMap<Character, Integer> map = new HashMap<>();
			    	map.put('b', 5);
			    	map.put('e', 3);
			    	map.put('d', 6);
			    	System.out.println(map);
			        System.out.println("Size of map is : "+map.size());
			    }  	
			}

Output :

Get the Size of the HashMap in Java
Output of size() function

In output, map contains 3 <Key,Value> pairs. Therefore, the size of the map is 3.

Remove All Elements of the HashMap Using Clear Method

the clear() method removes all the pairs, Which are stored in HashMap.

Code :

            package newPackage;
			import java.util.HashMap;
			import java.io.*;
			import java.lang.*;
			
			class BeeTechnical
			{
			    public static void main(String args[])
			    {
			    	HashMap<Character, Integer> map = new HashMap<>();
			    	map.put('b', 5);
			    	map.put('e', 3);
			    	map.put('d', 6);
			    	System.out.println("Map initially : "+map);
			    	map.clear();
			        System.out.println("Map after using clear() function : "+map);
			    }  	
			}

Output :

Remove all elements in the HashMap in Java
output of clear() method

It can be verified by seeing the output, That no element is there after using the clear() function.

keySet() and values() function

keySet() and values() methods return the set of keys and values in output respectively.

Code :

        package newPackage;
        import java.util.HashMap;
        import java.io.*;
        import java.lang.*;

        class BeeTechnical
        {
            public static void main(String args[])
            {
                HashMap<Character, Integer> map = new HashMap<>();
                map.put('b', 5);
                map.put('e', 3);
                map.put('d', 6);
                System.out.println("Map initially : "+map);
                System.out.println("All keys in map : "+map.keySet());
                System.out.println("All values in map : "+map.values());
            }   
        }

Output :

HashMap in Java, Complete Guide | 2022 1
Output of keySet() and values() method

ContainsKey() and ContainsValue() Method

As it is clear by the name of methods, They return a boolean value of the basis of that key or value is present in the map or not.

Code :

        package newPackage;
        import java.util.HashMap;
        import java.io.*;
        import java.lang.*;

        class BeeTechnical
        {
            public static void main(String args[])
            {
                HashMap<Character, Integer> map = new HashMap<>();
                map.put('b', 5);
                map.put('e', 3);
                map.put('d', 6);
                System.out.println("Map initially : "+map);
                System.out.println("Map contains Key 'b' : "+map.containsKey('b'));
                System.out.println("Map contains Key 'a' : "+map.containsKey('a'));
                System.out.println("Map contains value 10 : "+map.containsValue(10));
                System.out.println("Map contains value 6 : "+map.containsValue(6));
            }   
        }

Output :

output of containsKey() and containsValue()
output of containsKey() and containsValue()

Replace Pair in HashMap

Code :

        package newPackage;
        import java.util.HashMap;
        import java.io.*;
        import java.lang.*;

        class BeeTechnical
        {
            public static void main(String args[])
            {
                HashMap<Character, Integer> map = new HashMap<>();
                map.put('b', 5);
                map.put('e', 3);
                map.put('d', 6);
                System.out.println("Map initially : "+map);
                System.out.println("Old stored Value related to Key 'd' : "+map.get('d'));
                //Replacing old value 6 with new value 7 corresponding to key 'd' 
                map.replace('d', 7);
                System.out.println("New stored Value related to Key 'd' : "+map.get('d'));
            }   
        }

Output :

HashMap in Java, Complete Guide | 2022 2
Output of replace() function

In the output, It can be verified that we successfully changed the old value 6 replacing it with a new value 7 via using replace() method.

So far till now, We have seen the in-built method of HashMap. Let us take two more important things related to HashMap, Which are traversing and searching.

Traversing in HashMap Using Loop

We traverse the HashMap by using entrySet(). We traverse the map by using each loop by creating a variable of EntrySet<K, V> type.

Below the code is provided as a demonstration of traversing.

Code :

            package newPackage;
			import java.util.HashMap;
import java.util.Map;
import java.io.*;
			import java.lang.*;
			
			class BeeTechnical
			{
			    public static void main(String args[])
			    {
			    	HashMap<Character, Integer> map = new HashMap<>();
			    	map.put('b', 5);
			    	map.put('e', 3);
			    	map.put('d', 6);
			    	map.put('z', 1);
			    	map.put('h', 99);
			    	map.put('w', 80);
			    	System.out.println("Map : "+map);
			    	for(Map.Entry<Character, Integer> set : map.entrySet())
			    	{
			    		System.out.println("Key = "+set.getKey()+" Value = "+set.getValue());
			    	}
			    }  	
			}

Output :

Traversing on HashMap
Traversing on map

Searching in a HashMap Using Loop

Searching in the map is done by traversing and checking <key, Value> pair one by one as we do in linear search. The code below is provided as a demonstration.

Code :

            package newPackage;
			import java.util.HashMap;
import java.util.Map;
import java.io.*;
			import java.lang.*;
			
			class BeeTechnical
			{
			    public static void main(String args[])
			    {
			    	HashMap<Character, Integer> map = new HashMap<>();
			    	Character Key = 'z';
			    	Integer Value = 1;
			    	boolean flag=false;
 			    	map.put('b', 5);
			    	map.put('e', 3);
			    	map.put('d', 6);
			    	map.put('z', 1);
			    	map.put('h', 99);
			    	map.put('w', 80);
			    	System.out.println("Map : "+map);
			    	for(Map.Entry<Character, Integer> set : map.entrySet())
			    	{
			    		
			    		if(set.getKey()==Key&&set.getValue()==Value)
			    		{
			    			flag=true;
			    			break;
			    		}
			    	}
			    	System.out.println("Pair <z, 1> found in the map : "+flag);
			    }  	
			}

Output :

Search data in HashMap in Java
Search data in HashMap in Java

In the code above, We created variables Key and Value to find if that <Key, Value> pair exists in the map or not. We created a variable flag of the boolean data type to mark it true If the pair is found. In the output, we can see that flag shows true Because pair <‘z’, 1> exists in the map.

Conclusion

The article provided information about HashMap, its operation, some built-in methods connected to it via codes, as well as their output. Additionally, we carry out certain fundamental activities like map navigation and search.

0 0 votes
Article Rating
Subscribe
Notify of
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback
1 month ago

[…] you use Python, PHP, C#, Java, etc. Everywhere uses SQL, and the majority of interviewers ask SQL interview questions in most […]