VOOZH about

URL: https://www.javacodegeeks.com/2022/02/difference-between-function-andthen-and-function-compose.html

⇱ Difference between Function.andThen and Function.compose - Java Code Geeks


here are two different ways to mix functions in Java:

  • using andThen
  • using compose

It is important to understand the difference between the two.

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

composefunction1.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);
System.out.println(result);
 
Function<Double, Double> squareComposeCube = half.compose(twice);
result = squareComposeCube.apply(3d);
System.out.println(result);

The output for the above will be:

Published on Java Code Geeks with permission by Mohamed Sanaulla, partner at our JCG program. See the original article here: Difference between Function.andThen and Function.compose

Opinions expressed by Java Code Geeks contributors are their own.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

👁 Photo of Mohamed Sanaulla
Mohamed Sanaulla
February 12th, 2022Last Updated: February 8th, 2022
1 2,607 1 minute read
Subscribe

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

1 Comment
Oldest
Newest Most Voted
Eduard
4 years ago

I think you could have used a far better example without resorting to floating point non trivial arithmetic, now you are forcing your readers to use a calculator to double check the result 2.25 and 4.5.

2
Reply
Back to top button
Close
wpDiscuz