Replace put(..) with putIfAbsent(..)

Properties

Property Value
First seen in jSparrow version 2.3.0
Minimum Java version 8
Remediation cost 2 min

Description

If map.put(..) is wrapped with a condition verifying the existence of an element, one can use map.putIfAbsent(...) instead.

Benefits

Makes the code more readable, by using Java 8 extensions of Map interface.

Requirement & Tags

Requirements

Java 8

Code Changes

Default

Pre

if (!map.containsKey(aKey)){
    map.put(aKey, aValue);
}

Post

map.putIfAbsent(aKey, aValue);

No Block present

Pre

if (!map.containsKey(aKey))u
    map.put(aKey, aValue);

Post

map.putIfAbsent(aKey, aValue);

Including Null Checks

Pre

V v = map.get(key);
if (v == null) {
     v = map.put(key, value);
}
return v;

Post

map.putIfAbsent(key, value);
return v;

Limitations

The rule can be applied if a map type is present, a call to map.put(..) is present, and that call is wrapped in an if-Statement.