What is Consumer<T> and When to Use It
You'll learn what the Consumer functional interface is and when it's the right tool for operations that act on data without producing a return value.
The Core Idea
Consumer<T> is a functional interface designed for operations that accept an input but return nothing. Think of it like a black hole for data—it takes something in and does something with it (like printing, saving, or modifying), but doesn't give you anything back.
The interface has a single abstract method:
void accept(T t)
Unlike Function<T, R> which transforms input into output, Consumer<T> is all about side effects: actions that affect the outside world or modify state.
When to Use Consumer<T>
You use Consumer<T> when you want to perform an action on each element without needing a result:
Consumer<String> printer = s -> System.out.println(s);
printer.accept("Hello"); // Prints: Hello
Common scenarios include:
- Printing or logging data
- Saving to a database
- Updating object state
- Sending messages or notifications
The forEach method you've used with streams actually takes a Consumer:
List<String> names = List.of("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name)); // Consumer as lambda
The Analogy
Think of Consumer<T> as a mail slot. You drop something in (the input), and it handles the item (prints it, stores it, processes it), but you don't get anything back. The focus is on what happens to the input, not on producing a return value.
Key Takeaway: Use Consumer<T> when you need to perform an action on input without returning a result—it's the functional interface for side-effect operations.