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
Syntax
map.remove(key)
Parameters
| Parameter | Description |
|---|---|
keyObject |
The key to remove. |
Return value
The removed value, or null.
Examples
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.
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
| Version | Change |
|---|---|
| Java Java 1.0 | Added |
Related
map.put()· Add a key-value pair, or replace the value if the key already exists. Returns the previous value or null.- Java HashMap · tutorial