Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java Predicate and Lambda

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();
like image 903
Taobitz Avatar asked Dec 05 '18 13:12

Taobitz


People also ask

What is a predicate with lambda expression in Java?

Predicate<T> is a generic functional interface that represents a single argument function that returns a boolean value (true or false). This interface available in java. util. function package and contains a test(T t) method that evaluates the predicate of a given argument.

Is a predicate A lambda?

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

What is use of predicate in Java?

The predicate is a predefined functional interface in Java defined in the java. util. Function package. It helps with manageability of code, aids in unit-testing, and provides various handy functions.

Is predicate a functional interface?

Interface Predicate<T> Functional Interface: This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. Represents a predicate (boolean-valued function) of one argument.


1 Answers

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.

like image 89
Naman Avatar answered Nov 11 '22 18:11

Naman