繁体   English   中英

理解lambdas和/或谓词

[英]Understanding lambdas and/or predicates

我是Java 8的新手,我正试图解决为什么最后一次测试是错误的。

@Test
public void predicateTest() {
    Predicate<Boolean> test1 = p -> 1 == 1;
    Predicate<Boolean> test2 = p -> p == (1==1);

    System.out.println("test1 - true: "+test1.test(true));
    System.out.println("test1 - false: "+test1.test(false));
    System.out.println("test2 - true: "+test2.test(true));
    System.out.println("test2 - false: "+test2.test(false));
}

输出

test1 - true: true

test1 - false: true

test2 - true: true

test2 - false: false

你的第一个Predicate

Predicate<Boolean> test1 = p -> 1 == 1;

可以表示为

Predicate<Boolean> test1 = new Predicate<Boolean>() {
    @Override
    public boolean test(Boolean p) {
        return true; // since 1==1 would ways be 'true'
    }
};

因此无论您传递给上述test方法的价值如何,它始终只返回true

另一方面,第二个Predicate

Predicate<Boolean> test2 = p -> p == (1==1);

可以表示为

Predicate<Boolean> test2 = new Predicate<Boolean>() {
    @Override
    public boolean test(Boolean p) {
        return p; // since 'p == true' would effectively be 'p'
    }
};

因此,无论您将传递给上述test方法的boolean值,它都将按原样返回


然后,您可以关联如何调用匿名类的每个实例test1test2相对应方法test以及可能的输出。

这是假的,因为pfalse1==1true所以:

false == true计算结果为false。

换句话说,当您使用false作为参数调用此函数时:

 Predicate<Boolean> test2 = p -> p == (1==1);

它可以看作:

 Predicate<Boolean> test2 = p -> false == (1==1);

顺便说一句,上面的谓词将返回你传递的任何输入,所以基本上它是:

Predicate<Boolean> test2 = p -> p;

谓词test1 =值 - > 1 == 1;

谓词test2 =值 - >值==(1 == 1);

测试用例 :System.out.println(“test2 - false:”+ test2.test(false));

输出 :false

说明

您正在使用“false”调用test2方法,因此您的方法的执行将如下所示:

                   false == (1==1)  => false == true => false

所以最终的答案是错误的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM