I keep finding methods having code like this:
public boolean checkSomethingForCollection(Collection<Something> things){
for(Something thing:things){
boolean satisfiesCondition = check(thing);
if(satisfiesCondition){
return true;
}
}
return false;
}
private static boolean check(Something something){
//omitted...
}
I am fully aware of the fact that the public method will stop by reaching 'return' if the check(..) returns true, but it still looks ugly to me.
What would be preferable? Using break; instead to have one return only, or refactor to something else? Having
if(booleanExpression){
return true;
}
just makes me sick.
Java streams in Java 8 make this pretty easy - the Stream.anyMatch
method taking a predicate is exactly what you want. In this case you can use a method reference to create a predicate from the check()
method.
public boolean checkSomethingForCollection(Collection<Something> things) {
return things.stream().anyMatch(this::check);
}
Here's a short but complete example:
import java.util.*;
public class Test {
private final int minLength;
private Test(int minLength) {
this.minLength = minLength;
}
public boolean checkAny(Collection<String> things) {
return things.stream().anyMatch(this::check);
}
private boolean check(String x) {
return x.length() >= minLength;
}
public static void main(String[] args) throws Exception {
Test t = new Test(5);
List<String> shortStrings = Arrays.asList("asd", "bcd", "foo");
List<String> mixedStrings = Arrays.asList("asd", "bcd", "this is long", "foo");
System.out.println(t.checkAny(shortStrings)); // false
System.out.println(t.checkAny(mixedStrings)); // true
}
}
See more on this question at Stackoverflow