Java 25 (LTS) reference · Map and HashMap Methods

Java Map remove() Method

Remove the entry for a key and return its value (or null). remove(key, value) only removes a matching pair.

Java 25 (LTS) Since Java 1.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

map.remove(key)

Parameters

ParameterDescription
key
Object
The key to remove.

Return value

The removed value, or null.

Examples

Remove by key
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> cart = new TreeMap<>(Map.of("mug", 1, "tea", 2));
        System.out.println(cart.remove("mug"));
        System.out.println(cart.remove("kettle"));
        System.out.println(cart);
    }
}

Output

1
null
{tea=2}

Run this on your computer — see “Get Started” for setup.

Remove entries that match a condition
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> scores = new TreeMap<>(Map.of("ana", 90, "ben", 40));
        scores.entrySet().removeIf(e -> e.getValue() < 50);
        System.out.println(scores);
    }
}

Output

{ana=90}

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 1.0Added

Was this page helpful?