JAVA HashMap Definitive Guide

JAVA HashMap is a very important topic to be learned as part to get better at Data structures and Algorithms. JAVA HashMap is a very commonly used data structure used in a variety of applications. The main advantage of using HashMap is that you can get the Value of a particular key in O(1).

If you want to know more about Big O Notations then click here. Hashmap is roughly equal to HashTable in JAVA. As Hashmap is a Hashtable implementation of Map in JAVA.

JAVA HashMap has two parameters Key and Value as shown below example. HashMap cannot have the same key but the same key in HashMap has the same value stored. So this implementation has constant-time performance for basic operations such as to get and put methods.

How to Declare HashMap in JAVA

Below is an example of how to declare the HashMap in Java.

HashMap<String,Integer> hashTable = new HashMap<>(); //Definition of HashMap

Available Methods of MAP oin JAVA

Below is the list of Methods implemented in the HashMap for use of this data structure. And also we’ll cover the example of the important methods.

  1. Put Method [put(K key, V value)]: this is used to add an element to HashMap.
  2. Get Method [get(Object key)]: This method is used the get the value stored at the specified key in the HashMap.
  3. HashMap(int initialCapacity): Constructs an empty HashMap with specified initial capacity and a default load factor of 0.75.
  4. Clear(): This method is used to remove all the mappings from the map.
  5. isEmpty(): This method is used to check if defined HashMap is empty or not. It returns a boolean which is either true or false.
  6. remove(Object key): This method removes the mapping for the key if present which is provided as input.
  7. replace(key, value): This method replaces the value in the given key if present on the map with some value.
  8. size (): This method returns the number of key-value entries present on this map.

Add Element to Map Using put Function

Once you have initialized the HashMap as above. Put method is initialized in Map class which is used to add the element in HashMap. Let’s get through an example to know how to add an element in HashMap in JAVA.

import java.util.HashMap;

public class Solution{
  public static void main(String[] args){
    HashMap<String, Integer> score = new HashMap<>();
    score.put("Adam",20);
    score.put("kelly",10);
    score.put("Tom",50);
    
    System.out.println(score); // This will print all the three Map entries we
    //made above.
  }
}

If the map previously had the same key-value then the put method will replace the old value with the new value.

Output:

{Adam=20, Tom=50, kelly=10}

Get Method of HashMap

Get method in HashMap of Java is used to get the value at specified key if the input key is present else null if no key is found in the defined HashMap. Let’s go through an example to understand it more.

import java.util.HashMap;

public class Solution{
  public static void main(String[] args){
    HashMap<String, Integer> score = new HashMap<>();
    score.put("Adam",20);
    score.put("kelly",10);
    score.put("Tom",50);
    
    Integer getValueOfTom = score.get("Tom");
    
    System.out.println(getValueOfTom); // This will print the value as 50 which is stored at key "Tom"
  }
}

But again if the key entered in method get is not present then the method will return null. So, it’s always important to take care of null returns as they can break your code.

Output:

50

Size Method of HashMap

Size method in HashMap is used to get the total number of the key-value pair existing in the HashMap. If there are no elements then 0 will be returned else its return type is an integer. Let’s go through the example by extending the above example to get the size of the hashmap score.

import java.util.HashMap;

public class Solution{
  public static void main(String[] args){
    HashMap<String, Integer> score = new HashMap<>();
    score.put("Adam",20);
    score.put("kelly",10);
    score.put("Tom",50);
    
    Integer getSizeOfHashMap = score.size();
    
    System.out.println(getSizeOfHashMap); // This will print the value as 3 which is size of hashmap
  }
}

Output:

3

How to Print Elements of HashMap using forEach in JAVA

Now if we need to move or iterate through all the elements or keys of HashMap we need to use an iterator to do so. In Java, forEach is used to iterate through a HashMap. This Performs the given action for each entry in the map until all the entries are been processed. We will see this example using Lamba.

import java.util.HashMap;

public class Solution{
  public static void main(String[] args){
    HashMap<String, Integer> score = new HashMap<>();
    score.put("Adam",20);
    score.put("kelly",10);
    score.put("Tom",50);
    
    score.forEach((k,v) -> System.out.println((k + " = " +v)));
    //Above line will print each key with all the values available for it.
  }
}

Output:

JAVA HashMap Definitive Guide

How to use Iterator in HashMap

Let’s see another example using the Iterator method to get all the values of elements or keys. This will give a better understanding of the beginner level.

import java.util.HashMap;
import java.util.*;

public class Solution{
  public static void main(String[] args){
    HashMap<String, Integer> score = new HashMap<>();
    score.put("Adam",20);
    score.put("kelly",10);
    score.put("Tom",50);
    
    //Define the iterator
    Iterator<Map.Entry<String, Integer>> iterator = score.entrySet().iterator();
    //Then until we'll get empty next value we'll loop through it
    while(iterator.hasNext()){
      Map.Entry<String, Integer> currentKeyValue = iterator.next();
      System.out.println(currentKeyValue.getKey() + " = " + currentKeyValue.getValue());
    }
    //Above line will print each key with all the values available for it.
  }
}

Output:

Adam = 20
Tom = 50
kelly = 10

How to Check If Key Exists in HashMap using containsKey method

Java HashMap containskey method is used to check if the input key is present in the HashMap or not. It’s a boolean method that returns True or False based on the input. Let’s go through an example for a better understanding.

import java.util.HashMap;

public class Solution{
  public static void main(String[] args){
    HashMap<String, Integer> score = new HashMap<>();
    score.put("Adam",20);
    score.put("kelly",10);
    score.put("Tom",50);
    
    boolean isKeyPresent = score.containsKey("Tom");
    System.out.println(isKeyPresent);
    //This will print 1 or true as TOM is present as key in score HashMap.
    
    isKeyPresent = score.containsKey("Jim");
    System.out.println(isKeyPresent);
    //This will print 0 or false as Jim is not present as key in score hashmap.
  }
}

Output:

true //Tom is present in the HashMap
false //Jim is not present in HashMap

How to Remove Key Value Pair in HashMap

Now if we want to remove a particular key-value pair from the HashMap we need to used the Remove method declared in Map Class. Let’s go through examples to understand how to remove an element from HashMap.

import java.util.HashMap;

public class Solution{
  public static void main(String[] args){
    HashMap<String, Integer> score = new HashMap<>();
    score.put("Adam",20);
    score.put("kelly",10);
    score.put("Tom",50);
    
    System.out.println(score); //This will print all the element of score
    
    //Now let's delete Kelly from the score hashmap.
    score.remove("kelly");
    
    System.out.println(score); //This will print all the elements except kelly as it is delete from 
    // the hashmap
  }
}

Output:

{Adam=20, Tom=50, kelly=10} //Before Deleting
{Adam=20, Tom=50}

That’s it from today’s tutorial on JAVA 8 Edition HashMap. We’ll be updating this post in the future for more functions. If you want to understand or want any specific function to be covered, then please feel free to provide your comments below.

Also, please follow us on Twitter and Facebook. You can also ask questions there we’ll try to provide answer’s there. Please share and bookmark this page for more awesome content ahead.

If you want to read our tutorial on JAVA ArrayList please click here.

Share your love

2 Comments

Leave a Reply