Files
openide/java/java-impl/resources/inspectionDescriptions/Java8MapApi.html
2025-02-05 04:43:28 +00:00

58 lines
2.3 KiB
HTML

<html>
<body>
Reports common usage patterns of <code>java.util.Map</code> and suggests replacing them with:
<code>getOrDefault()</code>, <code>computeIfAbsent()</code>, <code>putIfAbsent()</code>, <code>merge()</code>, or <code>replaceAll()</code>.
<p>Example:</p>
<pre><code>
map.containsKey(key) ? map.get(key) : "default";
</code></pre>
<p>After the quick-fix is applied:</p>
<pre><code>
map.getOrDefault(key, "default");
</code></pre>
<p>Example:</p>
<pre><code>
List&lt;String&gt; list = map.get(key);
if (list == null) {
list = new ArrayList&lt;&gt;();
map.put(key, list);
}
</code></pre>
<p>After the quick-fix is applied:</p>
<pre><code>
map.computeIfAbsent(key, localKey -> new ArrayList&lt;&gt;());
</code></pre>
<p>Example:</p>
<pre><code>
Integer val = map.get(key);
if (val == null) map.put(key, 1);
else map.put(key, val + 1);
</code></pre>
<p>After the quick-fix is applied:</p>
<pre><code>
map.merge(key, 1, (localKey, localValue) -> localValue + 1);
</code></pre>
<p>Example:</p>
<pre><code>
for (Map.Entry&lt;String, String&gt; entry : map.entrySet()) {
map.put(entry.getKey(), transform(entry.getValue()));
}
</code></pre>
<p>After the quick-fix is applied:</p>
<pre><code>
map.replaceAll((localKey, localValue) -> transform(localValue));
</code></pre>
<!-- tooltip end -->
<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
<b>Suggest replacement even if lambda may have side effects</b> option 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>
</body>
</html>