Consumer vs Function: When Not to Return
You'll learn when to choose Consumer for actions versus Function for transformations.
The Core Difference
Think of Consumer as a worker who completes a task (printing, saving, logging) without giving you anything back. A Function is like a factory machine that takes raw materials and produces something new. The key distinction: does your operation need to return a transformed value, or just do something?
When to Use Consumer
Use Consumer<T> when your goal is to perform a side effect without producing a result:
- Printing to console
- Logging to a file
- Updating a database
- Sending a notification
- Modifying mutable state
// Consumer: just DO something
Consumer<String> logger = message -> System.out.println("LOG: " + message);
logger.accept("User logged in"); // void return
When to Use Function
Use Function<T, R> when you need to transform input into output:
- Converting data types
- Calculating derived values
- Extracting properties
- Building new objects from existing ones
// Function: RETURN a transformed value
Function<String, Integer> lengthCalculator = str -> str.length();
Integer result = lengthCalculator.apply("Hello"); // returns 5
The Decision Rule
Ask yourself: "Am I producing a new value, or just doing something with this value?"
- Producing/transforming →
Function<T, R> - Acting/performing →
Consumer<T>
If you find yourself writing a Function that always returns null or ignoring its return value, you probably need a Consumer instead.
Key Takeaway: Use Consumer when your operation's purpose is a side effect with no return value; use Function when you need to transform input into a meaningful output result.