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

# 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.

# Tags

# 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))
    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;

# Bytecode JDK 1.8

Pre

public void original(Map<String, String> map, String newKey, String newValue) {
    if(!map.containsKey(newKey)) {
        map.put(newKey, newValue);
    }
}
 0 aload_1
 1 aload_2
 2 invokeinterface #2 <java/util/Map.containsKey> count 2
 7 ifne 19 (+12)
10 aload_1
11 aload_2
12 aload_3
13 invokeinterface #3 <java/util/Map.put> count 3
18 pop
19 return

Post

public void transformed(Map<String, String> map, String newKey, String newValue) {
    map.putIfAbsent(newKey, newValue);
}
0 aload_1
1 aload_2
2 aload_3
3 invokeinterface #4 <java/util/Map.putIfAbsent> count 3
8 pop
9 return

# 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.

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

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