Difference between Function.andThen and Function.compose

There are two different ways to mix functions in Java:

  • using andThen
  • using compose

It is important to understand the difference between the two.

andThen: function1.andThen(function2) will first apply function1 to the input and the result of this will be passed to the function2.

compose: function1.compose(function2) will first apply the input to the function2 and the result of this will be passed to the function1

When they are used for operations that are not commutative then you will end up with totally different results.

You can see that in the example below:

Function<Double, Double> half = (a) -> a / 2;
Function<Double, Double> twice = (a) -> a * a;

Function<Double, Double> squareAndThenCube = half.andThen(twice);
Double result = squareAndThenCube.apply(3d);

Function<Double, Double> squareComposeCube = half.compose(twice);
result = squareComposeCube.apply(3d);

The output for the above will be:


Categories: Java

Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: