The accept Method: Performing Side Effects
You'll learn how Consumer's accept method executes actions on values without returning anything.
What accept Does
The accept method is the heart of the Consumer<T> interface. Unlike Function which transforms and returns values, or Predicate which tests and returns true/false, Consumer takes a single input and performs an action—but returns nothing (void). It's designed specifically for side effects: printing, logging, updating state, or modifying external resources.
Think of it like a restaurant server taking your order. The server accepts your menu choices and does something with them (submits to kitchen, writes them down), but doesn't hand you anything back right then. The action happens, but there's no return value.
The Signature
void accept(T t)
The method takes a single parameter of type T and returns void.
Basic Examples
Consumer<String> printer = s -> System.out.println(s);
printer.accept("Hello"); // Prints: Hello
Consumer<Integer> doubleLogger = n -> System.out.println(n * 2);
doubleLogger.accept(5); // Prints: 10
Common Use Cases
You've already seen Consumer with streams—forEach takes a Consumer to perform an action on each element:
List<String> names = List.of("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name)); // Each name printed
The lambda name -> System.out.println(name) is a Consumer<String> being passed to forEach, which calls accept on each element.
Key Takeaway: The accept method is Consumer's sole abstract method that executes side-effect operations on a single input value without returning anything, making it perfect for actions like printing, logging, or updating external state.