Remove Entry from HashMap Java

In this post, we will learn how to remove an entry from HashMap in Java with an example.

We use the following HashMap class methods to remove an entry from HashMap:

  • Remove a key from a HashMap remove(Object key)
  • Remove a key from a HashMap only if it is associated with a given value | remove(Object key, Object value)

Remove Entry from HashMap Java

import java.util.LinkedHashMap;
import java.util.Map;

public class RemoveKeysFromHashMapExample {
    public static void main(String[] args) {
      Map<String, String> userCityMapping = new LinkedHashMap<String, String>();

         userCityMapping.put("John", "New York");
         userCityMapping.put("Ramesh", "Pune");
         userCityMapping.put("Steve", "London");

         System.out.println("userCityMapping HashMap : " + userCityMapping);
         
        // Remove a key from the HashMap
        String userName = "Ramesh";
        userCityMapping.remove(userName);

        // remove entry - key-value pair
        boolean isRemoved = userCityMapping.remove("John", "New York");
        
        System.out.println(" entry removed : " + isRemoved);
        
        System.out.println("userCityMapping HashMap After removed : " + userCityMapping);
    }
}

Output

userCityMapping HashMap : {John=New York, Ramesh=Pune, Steve=London}
 entry removed : true
userCityMapping HashMap After removed : {Steve=London}

Reference



Comments