Avoid Adding Null Values Using computeIfAbsent()
and computeIfPresent()
in Maps
What is it?
The misuse of computeIfAbsent()
and computeIfPresent()
methods on Java Maps to add null
values can lead to unexpected behavior. These methods were designed to simplify conditional additions to a Map but do not support adding null
values directly.
Why apply it?
Using these methods improperly can result in the absence of expected entries or unintended Map entry removals, leading to bugs and maintenance issues in the code.
How to fix it?
Use traditional approaches with containsKey()
checks and conditional put()
calls to handle null
values explicitly, ensuring that Map entries are added as intended.
Examples
Example 1:
Negative
This negative example uses computeIfAbsent()
with a lambda returning null
, which will not insert the key-value pair in the map.
import java.util.HashMap;
import java.util.Map;
public class Example {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
String key = "testKey";
map.computeIfAbsent(key, k -> null); /* Noncompliant */
System.out.println("Map size: " + map.size()); // Outputs: Map size: 0
}
}
Example 2:
Positive
This positive example shows the use of containsKey
before adding null
to a map explicitly with put()
.
import java.util.HashMap;
import java.util.Map;
public class Example {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
String key = "testKey";
if (!map.containsKey(key)) {
map.put(key, null); /* Compliant */
}
System.out.println("Map size: " + map.size()); // Outputs: Map size: 1
}
}
Negative
This negative example uses computeIfPresent()
improperly, which will remove the entry if the lambda returns null
.
import java.util.HashMap;
import java.util.Map;
public class Example {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("testKey", "value");
String key = "testKey";
map.computeIfPresent(key, (k, v) -> null); /* Noncompliant */
System.out.println("Map contains key: " + map.containsKey(key)); // Outputs: false
}
}
Example 3:
Positive
This positive example checks if a key is present before replacing its value to null
, using put()
safely.
import java.util.HashMap;
import java.util.Map;
public class Example {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("testKey", "value");
String key = "testKey";
if (map.containsKey(key)) {
map.put(key, null); /* Compliant */
}
System.out.println("Map contains key with null value: " + (map.get(key) == null)); // Outputs: true
}
}