Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Consumer

An action that takes a value and returns nothing.

Available since: Java 8

Syntax

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
}

Examples

An action and a chain of actions:

void main() {
    List<String> log = new ArrayList<>();
    Consumer<String> print = s -> IO.println("> " + s);
    Consumer<String> save = log::add;
    print.andThen(save).accept("started");
    IO.println(log);
}

Output:

> started
[started]

Notes

It is taken by forEach() and ifPresent(). andThen() joins several actions into one. For two arguments there is BiConsumer, for primitives IntConsumer.

See also

  • Supplier — A supplier: a no-argument function that returns a value.
  • Stream.forEach() — Runs an action for every stream element (a terminal operation).
  • Optional.ifPresent() — Runs an action only if a value is present.

In the tutorial

  • Functional interfaces — Functional interfaces in Java: the @FunctionalInterface annotation, the standard Function, Predicate, Consumer, Supplier and combining them.

Thanks for reading!

Donate to the site — we work hard for you.