ConcurrentHashMap Compute Null Removes Entry

Return null from a ConcurrentHashMap remapping function to remove the entry, keep absent keys absent, and replace existing values in place.

JavaData Integrity

Code

snippet
import java.util.concurrent.ConcurrentHashMap;

public class ComputeNullRemovesEntry {

    public static void main(String[] args) {
        ConcurrentHashMap<String, Integer> quota = new ConcurrentHashMap<>();
        quota.put("web", 10);
        quota.put("batch", 5);

        // remapping 返回 null:该 entry 被 removes——CHM 不允许存 null 值
        quota.compute("batch", (key, current) -> current <= 5 ? null : current);
        System.out.println("after null return: " + quota);

        // 非 null 返回值:常规替换
        quota.compute("web", (key, current) -> current + 1);
        System.out.println("after replace: " + quota);

        // key 缺席时 current 是 null:再返回 null 不会插入新条目
        quota.compute("ghost", (key, current) -> current == null ? null : current + 1);
        System.out.println("ghost present: " + quota.containsKey("ghost"));
    }
}

ConcurrentHashMap Compute Null Removes Entry, line by line

ConcurrentHashMap Compute Null Removes Entry comes down to the class ComputeNullRemovesEntry and the function main.

Caveats

  • No dependencies section needed; the standard library is the whole story.

Using it

The signature worth quoting: public static void main(String[] args)

The demo output is labeled (after null return:, after replace:, ghost present:) — every line you see comes from exactly one labeled operation.

Key statements

quota.compute("ghost", (key, current) -> current == null ? null : current + 1);
quota.compute("batch", (key, current) -> current <= 5 ? null : current);
ConcurrentHashMap<String, Integer> quota = new ConcurrentHashMap<>();

Interactive Tools for This Topic

FAQ

What does ConcurrentHashMap Compute Null Removes Entry print when run?
Running the file directly is enough — expect labeled output lines such as `after null return:`, `after replace:`, `ghost present:`.