Java Reference ยท Streams and Functional
Consumer and BiConsumer interfaces
Reference for java.util.function.Consumer and BiConsumer: accept(), andThen(), use with forEach, Map.forEach and Optional.ifPresent, plus side-effect cautions.
Consumer<T> is a functional interface for an operation that takes a value and returns nothing. Its method is void accept(T t). Because it returns nothing, a consumer exists for its side effect: printing, storing, sending, updating something. BiConsumer<T, U> takes two arguments with void accept(T t, U u).
You meet consumers in Iterable.forEach(), Map.forEach(), Stream.forEach(), Stream.peek(), Optional.ifPresent() and Optional.ifPresentOrElse().
Consumer<String> printer = s -> System.out.println("got " + s); printer.accept("data");
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
@FunctionalInterface public interface Consumer<T> { void accept(T t); default Consumer<T> andThen(Consumer<? super T> after); } @FunctionalInterface public interface BiConsumer<T, U> { void accept(T t, U u); default BiConsumer<T, U> andThen(BiConsumer<? super T, ? super U> after); }
| Member | Description |
|---|---|
accept(t) |
Performs the operation on the argument. |
andThen(after) |
Returns a consumer that runs this one, then after with the same argument. |
Returns: nothing (void). andThen() returns the combined consumer.
Usage notes
- Exceptions stop the chain. If the first consumer in
a.andThen(b)throws,bnever runs, and the exception reaches the caller. - Same argument for both.
andThendoes not pass a result along (there is none); both consumers receive the original value. - Side effects need care. Updating shared state from
Stream.forEach()in a parallel stream is a data race; prefer collecting results withcollect(). - Lambda that returns a value is still fine:
list::addreturns aboolean, but it fitsConsumerbecause the result is discarded in a statement-expression lambda or method reference. - Primitive versions:
IntConsumer,LongConsumer,DoubleConsumer, plusObjIntConsumer<T>and friends, avoid boxing; see primitive interfaces. - No null-safety.
Consumer.andThen(null)throwsNullPointerExceptionright away, not whenaccept()runs. - Compare with
Runnable:Runnabletakes no argument,Consumertakes one.