Java Map remove() Method Tutorial

In this section we will learn what the Map remove() method is and how to use it in Java.

What is Java Map remove() Method?

The Java Map remove() method is used to remove a key (and its paired value) from a Map object.

Java remove() Method Syntax:

V remove(Object key)

default boolean remove(Object key, Object value)

remove() Method Parameters:

This method has two variants, as you can see from the syntax section.

For the first syntax, we only need to set the key that we want to be removed from the Map. And it will be if the method found such key in that map object.

For the second variant, the method takes a second argument, which is the expected value of the target key. In this case, if the specified key was in the target map object and also had the expected value associated with, the key and its pair will be removed from the list.

remove() Method Return Value:

The return value of the first variant is the value of the key that was removed from the map.

For the second variant, the return value of this method is of type Boolean and is equal to true if the operation was a success (the entry was removed) or false if the operation failed.

remove() Method Exceptions:

UnsupportedOperationException: We get this exception if the remove method is not supported in the target Map object.

ClassCastException: We get this exception if the data type of either arguments was incompatible compared to the data type of the key or values in the target Map object.

NullPointerException: We get this exception if either key or value that we put as the argument of the method is null and the target Map object does not allow such value.

Example: using Map remove() method

import java.util.Map; 
import java.util.HashMap;
class Main{
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>();
        map.put("Omid","Doe");
        map.put("Jack","Bauer");
        map.put("Barack","Obama");
        map.put("Elon","Musk");
        map.put("Lex","Fridman");

        map.remove("Omid");
        map.remove("Lex");
        map.remove("Elon");
        map.forEach((k,v)->{
            System.out.println(k+" "+v);
        });
    }
}

Output:

Barack Obama

Jack Bauer
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies