使用Java谓词和Lambda [英] Using Java Predicate and 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屋!