Java HashMap remove() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashMap

Definition

In Java, remove(key) deletes the mapping for key from a HashMap and returns the value it had, or null if the key was not present. The map shrinks by one when something is removed.

The overload remove(key, value) removes the mapping only if key is currently mapped to value, and returns true or false. It is a safe "delete only if unchanged" operation.

An instance method of java.util.HashMap (class since Java 1.2): a hash table of key/value pairs with no guaranteed order, one null key, any number of null values, and no thread safety. The two-argument remove(key, value) was added in Java 8 as a default method of Map, and HashMap overrides it.

Syntax

Two overloads: by key, or by key and expected value.

Java
Map<String, String> phones = new HashMap<>();
phones.put("Bea", "555-0120");
String old = phones.remove("Bea");            // "555-0120"
boolean ok = phones.remove("Bea", "x");       // false (already gone)
CallWhat it does
map.remove(k)Removes k; returns the old value or null.
map.remove(k, v)Removes only if k maps to v; returns a boolean.
map.keySet().removeIf(test)Removes every mapping whose key passes the test.
it.remove()Removes the current entry during an Iterator loop.

Unlike List.remove(int), there is no index version: map.remove(1) on a Map<Integer, V> removes the key 1.

Library declarations
Java
// java.util.HashMap<K, V>
public V remove(Object key)

// Java 8+, default method in Map<K, V>, overridden by HashMap
public boolean remove(Object key, Object value)

Parameters

ParameterDescription
key (Object)The key whose mapping should be removed. May be null.
value (Object)Two-argument form only: the value the key must currently have.

Return Value

Return ValueDescription
V (one argument)The previous value, or null if there was no mapping (or it was null).
boolean (two arguments)true if the mapping was removed.

Compare with Similar Methods

Ways to delete mappings:

MethodHow it differs
clear()Removes every mapping at once.
computeIfPresent(k, f)Removes when the function returns null.
values().removeIf(test)Removes by a condition on the values.

Java Examples

Example 1 — Remove a Contact and Get the Old Number

Remove an existing contact, try to remove a missing one, and print what is left.

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

public class HashMapRemoveDemo {
    public static void main(String[] args) {
        Map<String, String> phoneBook = new HashMap<>();
        phoneBook.put("Amir", "555-0110");
        phoneBook.put("Bea", "555-0120");
        phoneBook.put("Cy", "555-0130");

        String removed = phoneBook.remove("Bea");
        System.out.println("removed Bea: " + removed);
        System.out.println("remove Zoe: " + phoneBook.remove("Zoe"));
        System.out.println("left: " + phoneBook + ", size " + phoneBook.size());
    }
}

How It Works

  1. Returns what was there. remove("Bea") deletes the entry and hands back Bea's number, so it can still be used or logged.
  2. Missing key is harmless. Zoe was never stored; remove returns null and the map is unchanged.
  3. Size drops by one. Only the Bea mapping was deleted, leaving two contacts.
  4. Printed in hash order. Cy is printed before Amir because of their buckets; the order is not part of the contract.

Example 2 — Free a Seat Only for the Right Person

remove(key, value) deletes a booking only when the seat belongs to the given person.

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

public class HashMapRemoveKeyValue {
    public static void main(String[] args) {
        Map<String, String> seats = new HashMap<>();
        seats.put("A1", "Kim");
        seats.put("A2", "Lou");

        System.out.println("remove(A1, Max): " + seats.remove("A1", "Max"));
        System.out.println("remove(A1, Kim): " + seats.remove("A1", "Kim"));
        System.out.println("remove(A9, Kim): " + seats.remove("A9", "Kim"));
        System.out.println("seats now: " + seats);
    }
}

How It Works

  1. Wrong owner. A1 belongs to Kim, so asking to remove it for Max fails with false and leaves the booking alone.
  2. Exact match. Key A1 with value "Kim" matches (values are compared with equals), so the mapping is removed and the result is true.
  3. No such seat. A9 does not exist, so the call returns false without throwing.
  4. Boolean, not a value. Unlike the one-argument form, this overload reports success or failure rather than returning the old value.

Example 3 — The ConcurrentModificationException Trap

Removing finished tasks inside a for-each loop fails part way; removeIf on the values view does it safely.

Java
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Map;

public class HashMapRemoveInLoop {
    public static void main(String[] args) {
        Map<Integer, String> tasks = new HashMap<>();
        tasks.put(1, "done");
        tasks.put(2, "open");
        tasks.put(3, "done");
        tasks.put(4, "open");

        try {
            for (Integer id : tasks.keySet()) {
                if (tasks.get(id).equals("done")) {
                    tasks.remove(id);
                }
            }
        } catch (ConcurrentModificationException e) {
            System.out.println("remove inside for-each -> ConcurrentModificationException");
        }
        System.out.println("after failed loop: " + tasks);

        tasks.values().removeIf(status -> status.equals("done"));
        System.out.println("after removeIf: " + tasks);
    }
}

How It Works

  1. Small Integer keys. The keys 1 to 4 hash to buckets 1 to 4, so the loop visits them in ascending order on current JDKs.
  2. First removal works. Task 1 is done, and tasks.remove(1) deletes it, but it also bumps the map's modification count.
  3. Next step fails. When the hidden iterator moves on to key 2, it sees the changed count and throws ConcurrentModificationException, so task 3 is never reached and stays in the map.
  4. Safe bulk removal. values().removeIf removes through the iterator internally, deleting task 3 without any exception.

Frequently Asked Questions

Call map.remove(key). It deletes the mapping and returns the old value, or null if the key was not present.
It removes the mapping only if the key is currently mapped to that value, and returns true when it did. It was added in Java 8.
You removed a key while a for-each loop was iterating over the map. Use Iterator.remove() or removeIf() on keySet(), values(), or entrySet().
No. It returns null (or false for the two-argument form) and leaves the map unchanged.
Use map.values().removeIf(v -> v.equals(target)); or entrySet().removeIf for conditions on keys and values.

Next: replace()

Change a value only if the key already exists.

replace() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

15 people found this page helpful