Why use Java8 Streams' consumer andThen method?

I’m new to Java 8 and want to understand what is the difference in performance between the two code snippets below.

Approach 1

List<String> list = Arrays.asList("aaa","cccc","bbbb");
List<String> list2 = new ArrayList<>();

list.stream().forEach(x -> {

Approach 2

Consumer<String> c1 = s -> list2.add(s);
Consumer<String> c2 = s -> System.out.println(s);


What are the performance benefits of using the andThen method? Is there a specific reason why the Java team created it?

The performance benefits of using the andThen method in Approach 2 are that it avoids creating an intermediate collection (list2) to store the elements, which can save memory and improve performance for large collections. The andThen method allows you to chain multiple operations together, which can be more efficient than performing them separately.

The Java team created the andThen method to provide a way to combine multiple operations into a single function, which can simplify code and improve readability. It is often used in functional programming to compose functions together.