Java Map compute function diferences

Albert GirĂ³ published on
2 min, 212 words

Categories: Documentation

Tags: java

Java Map compute functions

There are three functions related with compute compute , computeIfAbsent, computeIfPresent. Each one has its own porpouse:

Compute

With the funtion compute if a key doesn' exists will throw exception

Map<String, List<Integer>> data = new HashMap<>();
data.put("first", 10);
System.out.println(data.compute("first", (key, val) -> val + 1)); // {"first": 11}
System.out.println(data.compute("second", (key, val) -> val + 1)); // throw exception

ComputeIfPresent

It is similar to compute() but,It only apply the function on this entries that exists in the keySet. If we try to comute an entry that doesn't exists it won't do anything.

Map<String, Integer> data = new HashMap<>();
data.put("first", 10);
System.out.println(data.compute("first", (key, val) -> val.add(50))); // {"first": [10,50]}
System.out.println(data.compute("second", (key, val) -> val.add(50))); //do nothing

ComputeIfAbsent

Whit this function we get the key value or initialize it with the lambda we define.

Map<String, Integer> data = new HashMap<>();
data.put("first", 10);
data.compute("first", key -> new ArrayList()).add(50); // {"first": [10,50]}
data.compute("second", key -> new ArrayList()).add(50); // initialize the entrySet AND add to list -> {"second": [10,50]}

To summarize, this table show the diferences between them:

functionexisting keynon existing key
computeprocess defined lambdathrow exception
computeIfPresentprocess defined lambdanothing happends
computeIfAbsentreturn key valueinitialize key and return value