JAVA HashMap Definitive Guide Code Examples

JAVA HashMap is a very important topic to be learned as part to get better at Data structures and Algorithms.

The JAVA HashMap data structure is widely used in a wide range of applications. The main benefit of using HashMap is that you can get the value of a specific key in O(1) (Constant time).

In JAVA, Hashmap is roughly equivalent to HashTable. In JAVA, Hashmap is a Hashtable implementation of Map.

JAVA HashMap has two parameters, as shown in the example below: Key and Value. All keys in Hashmap are unique, and each key can store values that can be duplicated.

As a result, this implementation provides constant-time performance for basic operations like the get-and-put methods.

How to Declare HashMap in JAVA

In Java, here’s an example of how to declare a HashMap.

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

Available Methods of MAP in JAVA

The methods implemented in the HashMap for use are listed below. I will cover the important methods with code examples.

  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

After you’ve initialized the HashMap as described above. The Map class initializes the put method, which is used to add an element to HashMap. Let’s look at an example to see how to add an element to a 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 contained the same key value, the put method will replace it with the new value.

Output:

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

Get Method of HashMap

The get method in Java HashMap is used to get the value at the specified key if the input key exists, else the method will return Null if the key does not exist.

Let’s look at the code examples to better understand it.

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"
  }
}

However, if the key entered in method get does not exist, the method will return null. As a result, it’s critical to avoid null returns because they can break your code.

Output:

50

Size Method of HashMap

The 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

If we want to move or iterate through all of HashMap’s elements or keys, we must use an iterator.

ForEach is used in Java to iterate through a HashMap. This executes the specified action for each entry in the map until all entries have been processed. This will be demonstrated 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 look at another example where the Iterator method is used to get all of the values of elements or keys. This will help you understand the beginner level better.

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 the containsKey method

The containsKey() method is used to determine whether or not the input key exists in the HashMap. It’s a boolean method that returns True or False depending on the input.

Let’s look at the code example to get 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

To remove a specific key-value pair from the HashMap, we must use the Remove method defined in the Map Class. Let’s look at some examples to see how to remove an element from a 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 concludes today’s JAVA 8 Edition HashMap tutorial. If you have any questions or would like a specific function covered, please leave 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.

Further Read:

  1. Java ArrayList Code Examples

Leave a Comment