# Replace Map::get by Map::getOrDefault

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

# Tags

# Code Changes


String value = concurrentHashMap.get(key);
if(value == null) {
    value = defaultValue;


String value = concurrentHashMap.getOrDefault(key, defaultValue);

# Limitations

The rule applies only on map implementations that do not allow null values, namely:

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 MapGetOrDefault
First seen in jSparrow version 3.5.0
Minimum Java version 8
Remediation cost 2 min