避免if(condition)返回true的优选方法

why*_*ent 1 java

我一直在寻找具有以下代码的方法:

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...
}
Run Code Online (Sandbox Code Playgroud)

我完全清楚,如果check(..)返回true,公共方法将通过达到'return'来停止,但它对我来说仍然看起来很难看.

什么会更好?使用休息; 相反只有一个回报,或重构其他东西?有

if(booleanExpression){
    return true;
}
Run Code Online (Sandbox Code Playgroud)

只是让我生病

Mag*_*gus 6

你不能用"每个java"来做到这一点,但你可以通过这样的法线避免它:

boolean satisfiesCondition = false;
for (int i = 0; i < size && !satisfiesCondition; ++i) {
    satisfiesCondition = check(things[i]);
}

return satisfiesCondition;
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 5

Java 8中的Java流使得这非常简单 - Stream.anyMatch采用谓词的方法正是您想要的.在这种情况下,您可以使用方法引用从该check()方法创建谓词.

public boolean checkSomethingForCollection(Collection<Something> things) {
    return things.stream().anyMatch(this::check);
}
Run Code Online (Sandbox Code Playgroud)

这是一个简短而完整的例子:

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
    }    
}
Run Code Online (Sandbox Code Playgroud)