Which functional interface in Java returns a boolean value?

Which functional interface in Java returns a boolean value?

a) Function
b) Predicate
c) Consumer
d) Supplier

Answer:

b) Predicate

Explanation:

The Predicate functional interface in Java is used to evaluate a condition and returns a boolean value. It is typically used in situations where a decision needs to be made based on a condition, such as filtering elements in a collection. Here is an example:

Predicate<Integer> isPositive = (Integer x) -> x > 0; boolean result = isPositive.test(5);  // result is true

In this example, the Predicate evaluates whether a given integer is positive. The test method is used to apply the condition, returning a boolean result. The Predicate interface is widely used in functional programming, especially in the context of streams and filtering operations.

By using the Predicate interface, developers can write code that is more declarative and easier to understand. This is particularly beneficial in scenarios where complex filtering logic is needed, such as in data processing pipelines or user input validation.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top