Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Consumer<T> — an operation with no result value

Consumer<T> accepts one argument and returns no value. It represents actions with side effects; accept runs the operation, while andThen combines two operations that run in sequence.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

Consumer<T> action = value -> { /* side effect */ };
action.accept(value);
Consumer<T> combined = action.andThen(after);

java.util.function.Consumer<T> is a functional interface: a lambda or method reference can be assigned to it. T specifies the argument type. A typical use is a side effect, such as appending text to a buffer, rather than computing a result value.

Consumer.accept, declared as void accept(T t), performs the operation on the supplied argument. void means there is no result value, not that the operation returns null.

andThen(Consumer<? super T> after) returns a composed Consumer: when its accept is called, both operations receive the same argument, first the original operation and then after. An exception propagates to the caller; if the first operation throws, the second is not executed. Passing null as after causes NullPointerException.

In the example, assigning the result of andThen to combined does not change the buffer. Only combined.accept("Java") appends the text and then its length. The expected result is Java:4.

Examples

import java.util.function.Consumer;

public class Main {
    public static void main(String[] args) {
        StringBuilder log = new StringBuilder();
        Consumer<String> append = text -> { log.append(text); };
        Consumer<String> appendLength = text -> {
            log.append(":").append(text.length());
        };

        Consumer<String> combined = append.andThen(appendLength);
        combined.accept("Java");
        System.out.println(log);
    }
}

Result

Java:4

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources