In Java 8, Predicate, Consumer, and Supplier are functional interfaces introduced in the java.util.function
package. These interfaces are widely used with lambda expressions and form a core part of the functional programming features added in Java 8.
Predicate
- Definition: The
Predicate
interface represents a boolean-valued function that accepts a single argument. It has a single abstract method, test()
, which evaluates the predicate condition for the given argument and returns a boolean result. - Use Case: Predicates are commonly used to test conditions or filter elements in the Stream API.
- Example:
java
Predicate<String> isLengthGreaterThanFive = s -> s.length() > 5;
System.out.println(isLengthGreaterThanFive.test("Java")); // Output: false
- In this example, the
Predicate
checks whether the length of a string is greater than 5.
Consumer
- Definition: The
Consumer
interface represents an operation that takes a single input argument and returns no result. It has a single abstract method, accept()
, which performs the operation on the provided argument. - Use Case: Consumers are often used in the
forEach()
method of the Stream API to perform actions on each element of the stream. - Example:
java
Consumer<String> printUpperCase = s -> System.out.println(s.toUpperCase());
printUpperCase.accept("hello"); // Output: HELLO
- In this example, the
Consumer
converts the input string to uppercase and prints it.
Supplier
- Definition: The
Supplier
interface represents a supplier of results. It has a single abstract method, get()
, which takes no arguments and returns a result. It is commonly used to supply values on demand and can be useful for lazy initialization. - Use Case: Suppliers are used when you need to generate or retrieve values without accepting any input. They are often used in cases like generating random values, lazy loading, or fetching data from a source.
- Example:
java
Supplier<Double> randomValueSupplier = Math::random;
double randomValue = randomValueSupplier.get();
System.out.println(randomValue); // Output: (some random value between 0 and 1)
- In this example, the
Supplier
provides a random value between 0 and 1.
These interfaces — Predicate, Consumer, and Supplier — provide a way to encapsulate behaviors, making code more modular and easier to understand. They are frequently used in combination with the Stream API, as well as in other functional programming constructs in Java.
- Predicate is used for testing conditions.
- Consumer is used for performing actions.
- Supplier is used for supplying values on demand.