• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

How to remove an entry from a Java HashMap

August 31, 2023 //  by Talha Malik

The HashMap in Java is defined as a data structure that implements arrays and dictionaries. It stores and retrieves values based on keys whereas the keys must be unique. The example will provide a better interpretation of the Java HashMap.

For instance, we have a database of a company, the most important aspect in the database of a company is employee ID. Therefore, each employee ID is a key and the data of the employee for that ID is stored as a value in a HashMap. 

In Java, many operations can be performed on a HashMap, and one such operation is “removing an entry” from a HashMap.

We will remove specific entries from a Java HashMap using suitable examples in this write-up.

How to Remove/Delete an Entry From a Java HashMap?

The Java HashMap has a unique key and each key has a value stored in it. The stored values can be accessed, retrieved, added, or removed using that particular key. 

To remove an entry from a HashMap, the below-listed methods can be used in Java:

  • Method 1: Using HashMap remove() Method
  • Method 2: Using Iteration Method 

Method 1: Using HashMap remove() Method

In Java, a built-in method named “remove()” is used to delete any specific entry from a HashMap based on the specified key. Consider the following code snippet for a profound understanding of the stated method:

import java.util.HashMap;//The class to remove the entry
class RemoveEntry {
  public static void main(String[] args){
    HashMap<Integer, String> fields = new HashMap<>();//Use the put() method to insert the first mapping to the map
    fields.put(1, "AI");//Use the put() method to insert the second mapping to the map
    fields.put(2, "Data Science");//Use the put() method to insert the third mapping to the map
    fields.put(3, "Cyber Security");//print the fields using the println command
    System.out.println("Fields: " + fields);//mention the field that has to be removed
    fields.remove(3); //print the updated field
    System.out.println("Updated Fields:" + fields);
  }
}

In the above code:

  • HashMap is created to store Integer and String key values respectively.
  • The HashMap put() method helps to insert a key and its value into the HashMap.
  • The remove() method eliminates the value based on the specified key.
  • Original and modified outputs are printed on the screen using the printIn() function.

Output

The output above shows that the field named “Cyber Security” has been removed with the help of its key value which was 3.

Method 2: Using the Iteration Method to Remove an Entry From Java HashMap

This method involves iterating over the HashMap in order to remove an entry from Java HashMap. The examples mentioned below will help in better interpretation.

Example 1: Iteration Approach For Java 7 and Earlier Versions

import java.util.*;
public class iteration {
    public static void main(String[] args)
    {
        HashMap<Integer, String>
        h = new HashMap<>();//Use the put() method to insert the mapping to the map
        h.put(1, "Computer");
        h.put(2, "Science");
        h.put(3, "Information");
        h.put(4, "Technology");
        int removekey = 3;
        System.out.println("Original: " + h)
        Iterator<Map.Entry<Integer, String> >
            iterator = h.entrySet().iterator();//Use the while if statement on the iterator
        while (iterator.hasNext()) {
            Map.Entry<Integer, String>
                entry= iterator.next();
            if (removekey == entry.getKey()) {
                iterator.remove();
            }
        }//Print the modified fields on the screen.
        System.out.println("Modified: " + h);
    }
}

In the code above:

  • The key and values for the HashMaps are declared.
  • The value to be removed has been specified through its key.
  • Now look for the key at iteration to be equal to the specified key.
  • If the key is the same, remove that key along with its value from the HashMap.
  • Print the modified output on the screen using the “println()” function. 

Output

The output above shows that the value with the key number “3” has been successfully removed.

Example 2: Iteration Approach For Java 8 and Later Versions

import java.util.*;
public class iteration {//The main class in Java
    public static void main(String[] args)
    {//The Integer and String value to be declared in HashMap.
        HashMap<Integer, String> h = new HashMap<>();
        h.put(1, "Computer");
        h.put(2, "Science");
        h.put(3, "Information");
        h.put(4, "Technology");
        int keyToBeRemoved = 3;
        System.out.println("Original: " + h);
      h.entrySet()
            .removeIf(entry -> (keyToBeRemoved == entry.getKey()));
        System.out.println("Modified: " + h);
    }
}

The following code does not utilize the while loop as the previous piece of code. Instead, a syntax difference occurs for Java version 8 using a lambda expression.

Output

This article has explained in detail the different methods in order to delete specific entries from a Java HashMap.

Conclusion

To remove an entry from a HashMap, various approaches are used in Java, such as the remove() method, and iterating approach. For instance, the remove() method accepts a particular key as an argument and deletes its corresponding value from the HashMap. This write-up has demonstrated certain methods to delete an entry from the HashMap in Java.

Category: Java

Previous Post: « How to Use Basic Java BlockingQueue
Next Post: How to Check if two Strings are Anagrams in Java »

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

How to Use Optional.ofNullable() Method in Java

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact