Using Java Predicate and Lambda

Taobitz picture Taobitz · Dec 5, 2018 · Viewed 7.9k times · Source

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

Answer

CodeMatrix picture CodeMatrix · Dec 5, 2018

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