Common Use Cases: Printing and Logging
What You'll Learn
You'll discover how Consumer<T> naturally fits printing and logging operations, which are classic side-effect actions in Java programs.
Why Consumer Shines for Output Operations
Printing to the console and logging information are perfect examples of side effects—actions that don't return a value but do something observable. Since Consumer<T> exists specifically for operations that accept input and perform side effects, it's the ideal tool for these tasks.
Printing with Consumer
The most common use case is printing stream elements. Instead of writing a loop, you pass a Consumer to stream operations:
List<String> names = List.of("Alice", "Bob", "Charlie");
// Using Consumer for printing
names.forEach(System.out::println);
// Equivalent lambda form
names.forEach(name -> System.out.println(name));
Logging Operations
Consumer works beautifully for logging frameworks or custom logging logic:
List<Integer> prices = List.of(100, 200, 150);
// Custom logging consumer
Consumer<Integer> priceLogger = price ->
System.out.println("Processing price: $" + price);
prices.forEach(priceLogger);
Formatted Output
You can create specialized consumers for formatted output:
Consumer<String> debugPrinter = msg ->
System.out.println("[DEBUG] " + msg);
List<String> events = List.of("User login", "Data saved");
events.forEach(debugPrinter);
The Pattern
The pattern is simple: whenever you need to do something with each element (print it, log it, write it to a file) without producing a return value, Consumer is your interface. It separates the "what to do" (the consumer logic) from the "how to iterate" (the collection mechanism).
Key Takeaway: Consumer<T> is the standard choice for printing and logging operations because these are side-effect actions that consume input without producing output—exactly what the accept method models.