Skip to content
Tutorials Center
My learning

Topics

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().

Java
Consumer<String> printer = s -> System.out.println("got " + s);
printer.accept("data");

Try it

Java accept and andThen

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.

Java BiConsumer with maps

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

Java
@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, b never runs, and the exception reaches the caller.
  • Same argument for both. andThen does 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 with collect().
  • Lambda that returns a value is still fine: list::add returns a boolean, but it fits Consumer because the result is discarded in a statement-expression lambda or method reference.
  • Primitive versions: IntConsumer, LongConsumer, DoubleConsumer, plus ObjIntConsumer<T> and friends, avoid boxing; see primitive interfaces.
  • No null-safety. Consumer.andThen(null) throws NullPointerException right away, not when accept() runs.
  • Compare with Runnable: Runnable takes no argument, Consumer takes one.