Consumer in Java
In Java, the Consumer interface is a functional interface defined in the java.util.function package. It represents an operation that takes a single input argument and returns no result. As a functional interface, Consumer can be used for lambda expressions and method references.
- Single Abstract Method: The
Consumerinterface defines one abstract method,accept(T t), which takes an argument and performs some operation but does not return any result. - Generics: The
Consumerinterface is generic, allowing you to specify the type of the input object. - Usage: Commonly used in scenarios where an operation needs to be performed on an object (such as printing, modifying, etc.) without needing to return a result.
- Chaining Operations: The
Consumerinterface also provides theandThenmethod, allowing you to chain multipleConsumeroperations together.
Example
1 | java |
In this example, printConsumer is a Consumer<String> that takes a string as input and prints it to the console.
andThen Method Example
The andThen method of the Consumer interface can be used to create a sequence of Consumer operations:
1 | java |
In this example, printConsumerUpperCase first executes the printConsumer operation (printing the original string) and then executes the operation that converts the string to uppercase and prints it.
Practical Example
Suppose we have a list of strings and we want to print each string. We can use the Consumer interface to accomplish this:
1 | java |
In this example:
printConsumeris an implementation ofConsumerthat takes a string and prints it.- We use the
forEachmethod to iterate over the list of strings and applyprintConsumerto each string (i.e., print each string).
Usage Scenarios
The Consumer interface is commonly used in scenarios where an operation needs to be performed on an object without returning a result, such as iterating over collections to perform operations, executing side effects of functions, etc. Due to its simplicity, it is very common in Java code that follows a functional programming style.