Consumer
TL;DR
Consumer<T>is a built-in functional interface in thejava.util.functionpackage.- It takes one argument and returns nothing (
void). - It is primarily used to perform an action on an object (like printing, mutating state, or saving to a database).
- Its abstract method is
void accept(T t).
Concept
A Consumer does exactly what its name implies: it consumes data. You give it an object, it does some work with that object, and it doesn’t give anything back.
It is most commonly seen in the Iterable.forEach() and Stream.forEach() methods, where you want to execute a block of code for every item in a collection.
Examples
import java.util.List;
import java.util.function.Consumer;
public class ConsumerExample {
public static void main(String[] args) {
// Define a consumer that prints a string in uppercase
Consumer<String> printUpper = s -> System.out.println(s.toUpperCase());
printUpper.accept("hello"); // HELLO
// Real-world usage: forEach
List<String> cities = List.of("London", "Paris", "Tokyo");
// forEach expects a Consumer.
// We pass a lambda that consumes the string and prints it.
cities.forEach(city -> System.out.println(city));
// --- Chaining Consumers ---
Consumer<String> printLower = s -> System.out.println(s.toLowerCase());
// andThen() executes the first consumer, then the second consumer
Consumer<String> printBoth = printUpper.andThen(printLower);
printBoth.accept("JaVa");
// Output:
// JAVA
// java
}
}
Interview Questions
Q: What is a BiConsumer?
A: BiConsumer<T, U> is an interface that takes two arguments and returns nothing. Its abstract method is void accept(T t, U u). It is extremely common when iterating over a Map, as Map.forEach() requires a BiConsumer where the first argument is the Key, and the second argument is the Value.
Q: Can a Consumer modify the object it receives?
A: Yes. Although a Consumer returns void, it can absolutely modify the internal state of the object it was given (assuming the object is mutable). For example, a Consumer<User> could execute user.setActive(true);.