Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java Map.merge: combine a value or remove its mapping

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

Map.merge inserts a non-null value for an absent key, or remaps a present non-null value with a function whose null result removes the entry.

An explicit removal is not zero

The stock ledger first combines a current quantity of three with two new units. A later correction returns null from the merge function, which removes the key. containsKey distinguishes the absent mapping from a stored zero; get alone would return null in both an absent map and a nullable-value map.

This is a single-thread HashMap fixture. It does not turn a read-modify-write sequence into an atomic operation across threads, processes or a database. ConcurrentMap has implementation-specific atomicity contracts, and transactions are a separate persistence boundary.

Never use null as an accidental arithmetic result

The supplied merge value must be non-null. Validate stock quantities and overflow before mutating a real ledger. A remapping function with external side effects can run in contexts whose retry behavior differs; keep the function small and pure when possible.

Working program

Java
import java.util.HashMap;
import java.util.Map;
public class StockLedgerMerge {
    public static void main(String[] args) {
        Map<String, Integer> quantities = new HashMap<>();
        quantities.put("SKU-7", 3);
        quantities.merge("SKU-7", 2, Integer::sum);
        System.out.println("after delivery=" + quantities.get("SKU-7"));
        quantities.merge("SKU-7", 1, (current, correction) -> null);
        System.out.println("present=" + quantities.containsKey("SKU-7"));
    }
}

Output

Output
after delivery=5
present=false

Costs and boundaries

For this HashMap fixture, lookup and update have expected constant-time behavior with a suitable hash distribution; that is not a worst-case or cross-process guarantee. The remapping call is not a database transaction.

Common Mistakes

  • Do not treat removal as a numeric zero.
  • Do not assume a HashMap merge protects concurrent writers.
  • Do not hide overflow or invalid corrections inside a remapping function.

Read next

Java HashMap: keys, collisions, and update operations, Java ConcurrentHashMap: atomic updates and weakly consistent reads, Java equals and hashCode: stable value keys, Spring TransactionTemplate: roll back a failed multi-row change.

java
collections
map-merge-removal
Storage details