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

Use a Java Refactoring Tool

No license required

You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.

System-wide Refactoring

Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.

a drawn cute bird pointing at a graph that shows positive results

# Properties

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