| <html> | |
| <body> | |
| Reports common usage patterns of <code>java.util.Map</code> that could be replaced with Java 8 methods: | |
| <code>getOrDefault()</code>, <code>computeIfAbsent()</code>, <code>putIfAbsent()</code>, <code>merge()</code>, or <code>replaceAll()</code>. | |
| <p>Examples:</p> | |
| <ul> | |
| <li>The <b>Map.getOrDefault</b> method can be used in: | |
| <pre> | |
| String val = map.containsKey(key) ? map.get(key) : "none";</pre> | |
| </li> | |
| <li>The <b>Map.computeIfAbsent</b> method can be used in: | |
| <pre> | |
| List<String> list = map.get(key); | |
| if (list == null) { | |
| list = new ArrayList<>(); | |
| map.put(key, list); | |
| }</pre> | |
| </li> | |
| <li>The <b>Map.putIfAbsent</b> method can be used in: | |
| <pre> | |
| String val = map.get(key); | |
| if (val == null) map.put(key, newVal);</pre> | |
| </li> | |
| <li>The <b>Map.merge</b> method can be used in: | |
| <pre> | |
| Integer val = map.get(key); | |
| if (val == null) map.put(key, 1); | |
| else map.put(key, val + 1);</pre> | |
| </li> | |
| <li>The <b>Map.replaceAll</b> method can be used in: | |
| <pre> | |
| for (Map.Entry<String, String> entry : map.entrySet()) { | |
| map.put(entry.getKey(), transform(entry.getValue())); | |
| } | |
| </pre> | |
| </li> | |
| </ul> | |
| <p>Note that the replacement with <code>computeIfAbsent()</code> or <code>merge()</code> might work incorrectly for some <code>Map</code> | |
| implementations if the code extracted to the lambda expression modifies the same <code>Map</code>. 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.</p> | |
| <p>Also, due to different handling of the <code>null</code> value in old methods like <code>put()</code> and newer methods like | |
| <code>computeIfAbsent()</code> or <code>merge()</code>, semantics might change if storing the <code>null</code> value into given | |
| <code>Map</code> 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. | |
| </p> | |
| <!-- tooltip end --> | |
| <p>This inspection works only if the language level of the project or module is 8 or higher</p> | |
| <p><small>New in 2016.3</small></p> | |
| </body> | |
| </html> |