Maps: compute and computeIfPresent update in place

compute always runs, computeIfPresent only for existing keys, and returning null from either removes the entry.

Code
Map<String, Integer> scores = new TreeMap<>(Map.of("ava", 10, "ben", 20));

scores.compute("ava", (k, v) -> v == null ? 1 : v + 5);
scores.compute("new", (k, v) -> v == null ? 1 : v + 5);
System.out.println("after compute: " + scores);

scores.computeIfPresent("missing", (k, v) -> v + 100);
System.out.println("computeIfPresent on missing key does nothing: " + scores);

scores.compute("ben", (k, v) -> null);
System.out.println("returning null removes the entry: " + scores);
Output
after compute: {ava=15, ben=20, new=1}
computeIfPresent on missing key does nothing: {ava=15, ben=20, new=1}
returning null removes the entry: {ava=15, new=1}
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-30