Loop can be collapsed with Stream API
Reports loops which can be replaced with stream API calls using lambda expressions.
Such a replacement changes the style from imperative to more functional and makes the code more compact.
Example:
boolean check(List<String> data) {
for (String e : data) {
String trimmed = e.trim();
if (!trimmed.startsWith("xyz")) {
return false;
}
}
return true;
}
After the quick-fix is applied:
boolean check(List<String> data) {
return data.stream().map(String::trim).allMatch(trimmed -> trimmed.startsWith("xyz"));
}
This inspection only reports if the language level of the project or module is 8 or higher.
Inspection options
Option | Type | Default |
---|---|---|
Warn if only 'forEach' replacement is available | Checkbox | false |
Warn if the loop is trivial | Checkbox | false |
Inspection Details | |
---|---|
Available in: | IntelliJ IDEA 2023.3, Qodana for JVM 2023.3 |
Plugin: | Java, 233.SNAPSHOT |
Last modified: 13 July 2023