Java Consumer andThen()

In this guide, you will learn about the Consumer andThen() method in Java programming and how to use it with an example.

1. Consumer andThen() Method Overview

Definition:

The Consumer.andThen() method provides a way to compose two instances of Consumer, effectively chaining them together. After performing its operation, the first Consumer will pass its input to the second Consumer.

Syntax:

default Consumer<T> andThen(Consumer<? super T> after)

Parameters:

- after: The next Consumer operation to be executed after the current operation.

Key Points:

- The andThen() method allows for the sequential combination of multiple Consumer operations.

- If the andThen() operation's argument throws an exception, it is relayed to the caller.

- If the original Consumer (the one calling andThen()) throws an exception, the after Consumer will not be executed.

2. Consumer andThen() Method Example

import java.util.function.Consumer;

public class ConsumerAndThenExample {
    public static void main(String[] args) {
        Consumer<String> toUpperCase = s -> System.out.println(s.toUpperCase());
        Consumer<String> appendExclamation = s -> System.out.println(s + "!");

        // Chaining the two consumers
        Consumer<String> chainedConsumer = toUpperCase.andThen(appendExclamation);

        String input = "hello";
        chainedConsumer.accept(input);
    }
}

Output:

HELLO
hello!

Explanation:

In the provided example, we have two Consumer instances. The first, toUpperCase, converts a string to uppercase and prints it. 

The second, appendExclamation, appends an exclamation mark to the string and prints it. 

Using andThen(), we chain these two consumers together into chainedConsumer

When we call accept() on chainedConsumer, the input string "hello" is first transformed to "HELLO" by toUpperCase and then printed with an appended exclamation mark by appendExclamation.

Comments