Using Java Predicate and Lambda

爷,独闯天下 提交于 2020-06-11 21:53:47

问题


Why does the below code return Predicate<String> and not 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.

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();

回答1:


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();
    }
};



回答2:


If you really are willing to get a boolean though from the Predicate, you can use its test method:

Predicate<String> nonEmptyStringPredicate = s -> !s.isEmpty();
boolean val = nonEmptyStringPredicate.test("any"); // true

Predicate on the other hand is just a FunctionalInterface, that you've represented using a lambda expression.




回答3:


Lambda is like an anonymous class, so this:

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

Is like:

Predicate<String> nonEmptyStringPredicate = new Predicate<String>() {
    public boolean test(String s) {
        return !s.isEmpty();
    }
}



回答4:


Why does the below code return Predicate and not boolean?

This is because the type of the function (String s) -> !s.isEmpty() is a Predicate<String>, at this point you're simply defining a function (which says "given a String as input return a boolean value indication whether it's empty or not).

Note that at this point you're not evaluating anything hence the result is not a boolean but rather a function.

Definition of FI from the doc:

Functional interfaces provide target types for lambda expressions and method references. Each functional interface has a single abstract method, called the functional method for that functional interface, to which the lambda expression's parameter and return types are matched or adapted. Functional interfaces can provide a target type in multiple contexts, such as assignment context, method invocation, or cast context:

in order to get the "boolean result" you're seeking, you must first invoke the "functional method". example:

Predicate<String> nonEmptyStringPredicate = s -> !s.isEmpty();
boolean result = nonEmptyStringPredicate.test(""); 



回答5:


A predicate always returns a boolean so the only interesting value here is the input parameter which is a String.

See: https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html



来源:https://stackoverflow.com/questions/53633089/using-java-predicate-and-lambda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!