# Replace Map::get by Map::getOrDefault
# Properties
Property | Value |
---|---|
Rule ID | MapGetOrDefault |
First seen in jSparrow version | 3.5.0 |
Minimum Java version | 8 |
Remediation cost | 2 min |
# Description
Java 8 introduced Map::getOrDefault
(opens new window) which offers the possibility to return a default value if the map does not contain a mapping for the given key.
This rule replaces the invocations of Map::get
followed by a null-check with Map::getOrDefault
.
# Benefits
Makes the code more readable, by using Java 8 extensions of Map interface.
# Code Changes
Pre
String value = concurrentHashMap.get(key);
if(value == null) {
value = defaultValue;
}
Post
String value = concurrentHashMap.getOrDefault(key, defaultValue);
# Limitations
The rule applies only on map implementations that do not allow null
values, namely:
Attributes
(opens new window)ConcurrentHashMap
(opens new window)ConcurrentSkipListMap
(opens new window)Hashtable
(opens new window)Properties
(opens new window).
Automatic Application of This Rule
The automatic application of this rule is supported in the following jSparrow version:
# Tags
1
You & jSparrow