在if语句中检查将多个参数设为相同值的较短方法?

时间:2018-07-13 12:10:27

标签: java if-statement

是否有一种简单的方法可以将多个参数比较为相同的值? 为了说明我的意思,我编写了这段无效的代码,但却说明了我在寻找什么:

if ((arg1 && arg2 && arg3) > 0)

无需编写:

if (arg1 > 0 && arg2 > 0 && arg3 > 0)

在我看来,优点将更易于阅读代码,并且只需更改一个值即可。

7 个答案:

答案 0 :(得分:4)

一个巧妙的技巧是流式传输所有参数,并将allMatch与要检查的谓词一起使用:

if (IntStream.of(arg1, arg2m arg3).allMatch(x -> x > 0)) {

答案 1 :(得分:2)

假设它们是int变量:您可以使用流:

boolean gt3 = IntStream.of(arg1, arg2, arg3).allMatch(i -> i > 0);

longdouble的流类型也一样。

答案 2 :(得分:1)

如果这确实是您在代码中进行的 lot 处理,则可以使用signum来引入enum概念的扩展。

/**
 * Extends the signum function to multiple arguments
 * <p>
 * If all signums are the same then that will be returned.
 * <p>
 * If any are different - return Mixed.
 */
enum Sign {
    Negative, Positive, Zero, Mixed;

    public static Sign get(int n) {
        return n < 0 ? Negative : n == 0 ? Zero : Positive;
    }

    public static Sign get(int... n) {
        Sign first = get(n[0]);
        for(int i = 1; i < n.length; i++) {
            if(get(n[i]) != first) {
                return Mixed;
            }
        }
        return first;
    }
}

使用方式:

Sign.get(arg1, arg2, arg3) == Sign.Positive

答案 3 :(得分:0)

没有办法组合运算符来根据需要检查条件。只有数字once的一种方法可以是:

if(IntStream.of(arg1, arg2, arg3).allMatch(arg->arg>0)){
    //..
}

答案 4 :(得分:0)

如果您主要关注可读性,则可以将测试移至实用方法:

if ( allIntGreaterZero(arg1, arg2, arg3) ) {
    ...
}

public static boolean allIntGreaterZero(int... a) {
    return Arrays.stream(a).allMatch(i -> i > 0);
}

答案 5 :(得分:0)

首先,您可以使用Stream.of来执行此操作:

if (Stream.of(arg1, arg2, arg3).allMatch(arg -> arg > 0))
{
    System.out.println("Passed (if)");
}
else
{
    System.out.println("Not passed (else)");
}

但是您可以创建自己的“结构”以供使用:

checkIf(arg -> arg > 0, 
        () -> System.out.println("Passed (if)"), 
        () -> System.out.println("Not passed (else)"), 
        arg1, arg2, arg3);

这是上面使用的checkIf()的实现:

public static <T> void checkIf(Predicate<T> predicate, Runnable actionIfTrue, Runnable actionIfFalse, T... values)
{
    if (Stream.of(values).allMatch(predicate))
    {
        actionIfTrue.run();
    }
    else
    {
        actionIfFalse.run();
    }
}

答案 6 :(得分:-2)

使用变量作为比较值,则不必多次更改它。没有您想要的方式。