# Use Stream::filter
# Description
This rule transforms an if-Statement (without an else statement), which wraps the whole execution block of a Stream::forEach
method into a call to Stream::filter
with a lambda expression (Predicate) as parameter. This lambda is constructed using the expression from the if-Statement.
# Benefits
This rule provides an easier-to read alternative to filter items in a list.
# Tags
# Code Changes
Pre
List<String> list = Arrays.asList("foo", "bar");
list.stream().forEach(s -> {
if (s.length() > 3) {
System.out.println(s);
System.out.println(s + s);
}
});
Post
List<String> list = Arrays.asList("foo", "bar");
list.stream().filter((s)-> s.length() > 3).forEach((s)-> {
System.out.println(s);
System.out.println(s + s);
});
Use a Java Refactoring Tool
No license required
You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.
System-wide Refactoring
Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.
# Properties
Property | Value |
---|---|
Rule ID | LambdaForEachIfWrapperToFilter |
First seen in jSparrow version | 2.0.0 |
Minimum Java version | 8 |
Remediation cost | 5 min |