It's a common pattern to test the result of a ``++java.util.Map.get()++`` against ``++null++`` or calling ``++java.util.Map.containsKey()++`` before proceeding with adding or changing the value in the map. However the ``++java.util.Map++`` API offers a significantly better alternative in the form of the ``++computeIfPresent()++`` and ``++computeIfAbsent()++`` methods. Using these instead leads to cleaner and more readable code. *Note* that this rule is automatically disabled when the project's ``++sonar.java.source++`` is not 8. == Noncompliant Code Example ---- V value = map.get(key); if (value == null) { // Noncompliant value = V.createFor(key); if (value != null) { map.put(key, value); } } if (!map.containsKey(key)) { // Noncompliant value = V.createFor(key); if (value != null) { map.put(key, value); } } return value; ---- == Compliant Solution ---- return map.computeIfAbsent(key, k -> V.createFor(k)); ---- == Exceptions This rule will not raise an issue when trying to add ``++null++`` to a map, because ``++computeIfAbsent++`` will not add the entry if the value returned by the function is ``++null++``. == See Also * S6104 - Map "computeIfAbsent()" and "computeIfPresent()" should not be used to add "null" values. ifdef::env-github,rspecator-view[] == Comments And Links (visible only on this page) include::comments-and-links.adoc[] endif::env-github,rspecator-view[]