How to Use Consumer Interface in Java: Simple Guide
In Java,
Consumer is a functional interface used to perform an action on a given input without returning a result. You use it by implementing its accept() method, often with a lambda expression, to process data like printing or modifying values.Syntax
The Consumer interface is part of java.util.function package and has a single abstract method:
void accept(T t): Takes an input of typeTand performs an operation without returning anything.
You can implement it using a lambda expression or method reference.
java
Consumer<String> consumer = (String s) -> System.out.println(s); consumer.accept("Hello, Consumer!");
Output
Hello, Consumer!
Example
This example shows how to use Consumer to print each element of a list.
java
import java.util.function.Consumer; import java.util.List; public class ConsumerExample { public static void main(String[] args) { List<String> names = List.of("Alice", "Bob", "Charlie"); Consumer<String> printName = name -> System.out.println("Name: " + name); names.forEach(printName); } }
Output
Name: Alice
Name: Bob
Name: Charlie
Common Pitfalls
Common mistakes when using Consumer include:
- Trying to return a value from
accept(), which is void. - Not using lambda expressions or method references properly, causing verbose or unclear code.
- Misunderstanding that
Consumeronly performs actions and does not transform data.
java
/* Wrong: Trying to return a value (won't compile) */ // Consumer<String> consumer = s -> { return s.length(); }; /* Right: Just perform an action without returning */ Consumer<String> consumer = s -> System.out.println(s.length());
Quick Reference
| Feature | Description |
|---|---|
| Package | java.util.function |
| Method | void accept(T t) |
| Purpose | Perform an action on input without returning |
| Common Use | Printing, logging, modifying objects |
| Lambda Example | (input) -> System.out.println(input) |
Key Takeaways
Consumer is a functional interface with a void accept(T) method.
Use lambda expressions to define what action Consumer performs on input.
Consumer does not return a value; it only performs side effects.
Commonly used for operations like printing or modifying objects.
Avoid trying to return values inside the accept method.