使用Java谓词和Lambda [英] Using Java Predicate and Lambda

查看:116
本文介绍了使用Java谓词和Lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码返回Predicate<String>而不返回boolean?

Why does the below code return Predicate<String> and not boolean?

我的理解是,此处的!s.isEmpty()检查与谓词boolean test(T t);背道而驰.此处的返回类型为boolean.

My understanding is that the !s.isEmpty() check here is going against the Predicate boolean test(T t); The return type here is boolean.

所以在我的lambda中,我的nonEmptyStringPredicate是否不应该是boolean类型?显然不是,我只是想了解为什么不是这样.

So in my lambda should my nonEmptyStringPredicate not be of type boolean? Obviously, it's not, I'm just trying to understand why it's not.

Predicate<String> nonEmptyStringPredicate = (String s) -> !s.isEmpty();

推荐答案

在这种情况下,Predicate得到一个String作为参数,并返回一个boolean. 如果我们不将其写为lambda,它将看起来像这样:

A Predicate gets in this case a String as parameter and returns a boolean. In case we don't write it as lambda it would look like this:

Predicate<String> somePredicate = new Predicate<String>() {
    @Override
    public boolean test(String string) {
        return !string.isEmpty();
    }
};

这篇关于使用Java谓词和Lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆