Java Map remove() example

In this guide, you will learn about the Map remove() method in Java programming and how to use it with an example.

1. Map remove() Method Overview

Definition:

The remove() method of the Java Map interface removes the entry for the specified key from the Map if it is present.

Syntax:

V removedValue = map.remove(Object key);

Parameters:

- key: The key whose mapping is to be removed from the map.

Key Points:

- If the map contains a mapping for the specified key, this method returns the previously associated value.

- If the map doesn't contain the specified key, it returns null.

- The method allows null as a key. If the map contains a mapping for a null key, then this method can remove the key-value pair and return the value.

- Some map implementations, like HashMap, allow null keys and values, while others, like TreeMap, do not.

2. Map remove() Method Example

import java.util.HashMap;
import java.util.Map;

public class MapRemoveExample {
    public static void main(String[] args) {
        Map<String, String> fruitColors = new HashMap<>();

        // Populate the map
        fruitColors.put("Apple", "Red");
        fruitColors.put("Banana", "Yellow");
        fruitColors.put(null, "N/A");

        // Remove entries using keys
        System.out.println(fruitColors.remove("Apple"));  // Red
        System.out.println(fruitColors.remove("Banana")); // Yellow
        System.out.println(fruitColors.remove("Cherry")); // null
        System.out.println(fruitColors.remove(null));     // N/A

        // Print the remaining map
        System.out.println(fruitColors);                  // {}
    }
}

Output:

Red
Yellow
null
N/A
{}

Explanation:

In this example:

1. We create a HashMap and populate it with three key-value pairs. One of these pairs has a null key.

2. We then use the remove() method to remove entries associated with various keys:

- Removing the entry for "Apple" gives us its previously associated value Red.

- Removing the entry for "Banana" gives us Yellow.

- Trying to remove the entry for "Cherry" gives us null since "Cherry" is not in the map.

- Removing the entry with a null key gives us its value N/A.

3. In the end, the map is empty, as we've removed all the entries.

The remove() method is an essential tool when manipulating data in maps, allowing for the effective removal of key-value pairs based on a given key.

Related Map Interface methods

Java Map put() example
Java Map get() example
Java Map remove() example
Java Map containsKey() example
Java Map containsValue() example
Java Map keySet() example
Java Map values() example
Java Map entrySet() example

Comments