Functional Interface Predicate - Quiz

Total: 5 questions

1. 

When Predicate interface can be used?

A functional interface from java.util.function that takes one argument of type T and returns boolean. Used to evaluate an object against a condition, as in Stream.filter() or Collection.removeIf().

2. 

Use Predicate interface in lambda expression to verify whether integer is a negative number or not.

Predicate<Integer> negative = i -> i < 0;
System.out.println(negative.test(-6));
System.out.println(negative.test(6));
System.out.println(negative.test(0));
3. 

Enumerate default methods of the Predicate interface.

default Predicate<T> and(Predicate<? super T> other)
default Predicate<T> negate()
default Predicate<T> or(Predicate<? super T> other)
4. 

How does Predicate<T> differ from Function<T, Boolean>?

Predicate returns the primitive boolean, while Function<T, Boolean> returns the wrapper Boolean, which adds autoboxing and allows null. Predicate also provides and(), or(), negate() and the static factories isEqual() and not(), which Function does not have. Finally, JDK methods such as Stream.filter(), anyMatch() and Collection.removeIf() are declared with a Predicate parameter, so a Function<T, Boolean> cannot be passed to them.

5. 

Are both predicates always evaluated by and() and or()?

No. and() and or() are implemented with the && and || operators, so evaluation short-circuits: in a.and(b) the predicate b is not called when a returns false, and in a.or(b) it is not called when a returns true. That is why cheap and guarding checks must come first:

Predicate<String> notNull = Objects::nonNull;
Predicate<String> notBlank = s -> !s.isBlank();

Predicate<String> valid = notNull.and(notBlank); // null check goes first

The opposite order would throw a NullPointerException. Note also that a.and(null) throws NullPointerException at composition time, because the implementation starts with Objects.requireNonNull(other).

Page 1 of 1