Files
openide/java/java-impl/resources/inspectionDescriptions/StreamToLoop.html
Leonid Shalupov 40795fe787 IJI-2422: community/java: move resources under resources root
GitOrigin-RevId: 8b2b63fc6db476ca0c2cfe5cadd84db6c4236d0f
2025-02-05 04:43:28 +00:00

49 lines
1.9 KiB
HTML

<html>
<body>
Reports Stream API chains, <code>Iterable.forEach()</code>, and <code>Map.forEach()</code> calls that can be automatically converted into classical loops.
This can help to downgrade for backward compatibility with earlier Java versions.
<p><b>Example:</b></p>
<pre><code>
String joinNonEmpty(List&lt;String&gt; list) {
return list.stream() // Stream can be converted to loop
.filter(s -> !s.isEmpty())
.map(String::trim)
.collect(Collectors.joining(", "));
}
</code></pre>
<p>After the quick-fix is applied:</p>
<pre><code>
String joinNonEmpty(List&lt;String&gt; list) {
StringJoiner joiner = new StringJoiner(", ");
for (String s : list) {
if (!s.isEmpty()) {
String trim = s.trim();
joiner.add(trim);
}
}
return joiner.toString();
}
</code></pre>
<p>
Note that sometimes this inspection might cause slight semantic changes.
Special care should be taken when it comes to short-circuiting, as it's not specified how many elements will be actually read when
the stream short-circuits.
</p>
<!-- tooltip end -->
<p>Configure the inspection:</p>
<p>Use the <b>Iterate unknown Stream sources via Stream.iterator()</b> option to suggest conversions for streams with unrecognized source.
In this case, iterator will be created from the stream.
For example, when checkbox is selected, the conversion will be suggested here:</p>
<pre><code>
List&lt;ProcessHandle&gt; handles = ProcessHandle.allProcesses().collect(Collectors.toList());</code></pre>
<p>In this case, the result will be as follows:</p>
<pre><code>
List&lt;ProcessHandle&gt; handles = new ArrayList&lt;&gt;();
for (Iterator&lt;ProcessHandle&gt; it = ProcessHandle.allProcesses().iterator(); it.hasNext(); ) {
ProcessHandle allProcess = it.next();
handles.add(allProcess);
}
</code></pre>
<p><small>New in 2017.1</small></p>
</body>
</html>