java.util.Map
that could be replaced with Java 8 methods:
getOrDefault()
, computeIfAbsent()
, putIfAbsent()
, merge()
, or replaceAll()
.
Examples:
String val = map.containsKey(key) ? map.get(key) : "none";
List<String> list = map.get(key); if (list == null) { list = new ArrayList<>(); map.put(key, list); }
String val = map.get(key); if (val == null) map.put(key, newVal);
Integer val = map.get(key); if (val == null) map.put(key, 1); else map.put(key, val + 1);
for (Map.Entry<String, String> entry : map.entrySet()) { map.put(entry.getKey(), transform(entry.getValue())); }
Note that the replacement with computeIfAbsent()
or merge()
might work incorrectly for some Map
implementations if the code extracted to the lambda expression modifies the same Map
. By default,
the warning doesn’t appear if this code might have side effects. If necessary, enable the last checkbox to always show the warning.
Also, due to different handling of the null
value in old methods like put()
and newer methods like
computeIfAbsent()
or merge()
, semantics might change if storing the null
value into given
Map
is important. The inspection won't suggest the replacement when the value is statically known to be nullable,
but for values with unknown nullability the replacement is still suggested. In these cases, we recommended suppressing the warning
and adding an explanatory comment.
This inspection works only if the language level of the project or module is 8 or higher
New in 2016.3