Map computeIfAbsent and computeIfPresent methods are
convenient to avoid the cumbersome process to check if a key exists or not, followed by the addition of the entry. However, when the function used to
compute the value returns null
, the entry key->null
will not be added to the Map. Furthermore, in the case of
computeIfPresent
, if the key is present the entry will be removed. These methods should therefore not be used to conditionally add an
entry with a null value. The traditional way should be used instead.
This rule raises an issue when computeIfAbsent
or computeIfPresent
is used with a lambda always returning null.
Noncompliant code example
map.computeIfAbsent(key, k -> null); // Noncompliant, the map will not contain an entry key->null.
map.computeIfPresent(key, (k, oldValue) -> null); // Noncompliant
Compliant solution
if (!map.containsKey(key)) {
map.put(key, null);
}
if (map.containsKey(key)) {
map.put(key, null);
}