Search code examples
javalambdajava-8predicatefunctional-interface

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

Solution

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