CodeBlanks Logo Icon CodeBlanks

Consumer<T>

Learn consumer functions with Consumer<T>.

The Consumer<T> interface

Consumer<T> represents an action that takes a T value and returns nothing (void). Its single abstract method is accept. It is suited for side-effecting operations.

Example: Consumer<String> printer = s -> System.out.println(s);. Then printer.accept("Hello") prints Hello to the screen. Consumer is used to carry value-consuming code as a variable; for example as an argument to forEach.

Chaining Consumers with andThen

To run two Consumers in sequence you use andThen. The first Consumer consumes the value; then the second receives the same value. This is handy for running several actions in a single pass.

Example: printer.andThen(logger).accept("data"). First the value is printed, then it is logged. Both Consumers receive the same value; they run in order. This is a clean way to compose side effects.

Practice Print with a Consumer

Define a Consumer<String> that uses the lambda s -> System.out.println("Got: " + s). Then print the value by calling accept("Hello").

Starter code

Main.java
import java.util.function.Consumer;

// Define a printing Consumer
// Print the value with accept
// Output: Got: Hello

Sample solution

Main.java
import java.util.function.Consumer;

public class ConsumerExample {
    public static void main(String[] args) {
        Consumer<String> printer = s -> System.out.println("Got: " + s);
        printer.accept("Hello");
    }
}

Expected output

Got: Hello

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is the call method of Consumer<T>?

  • apply
  • test
  • accept Correct answer
  • get

Explanation: accept is Consumer's call method.

2 Complete the Consumer call

Question
Consumer<String> printer = s -> System.out.println(s);
printer.____("Merhaba");
Answer
Consumer<String> printer = s -> System.out.println(s);
printer.accept("Merhaba");

Explanation: accept is Consumer's call method.

3 Match the Consumer concepts

Term Meaning
Consumer<T> Takes T returns void
accept Call method
andThen Calls afterwards
BiConsumer<T,U> Takes two values

All lessons in Advanced