Difference between ‘compose’ and ‘andThen’ Function interface methods in Java

One of the most important features added to Java 8 was the Function interface. The developers can implement this interface by adding any functionality through the functional paradigm and execute it whenever necessary with few lines of code.

Using Function interface

Below is a simple example on how to use the Function interface in Java:

As you can see, the variable stringToUpperCase is an object of a Function interface implementation and it was created with the aim to transform any String in uppercase letters. Subsequently, that variable was used in two different situations, in the first one, the default method apply was used to execute that functionality in the personName variable, and in the last one, that variable was used as a parameter to the map method in the stream of animals list.



Default methods in the Function interface

The Function interface has four methods, two of which are used to create execution’s flows, concatenating functionalities through of the Decorator Design Pattern. They are compose and andThen methods.

Those two methods has almost same functionality, but there’s a small but relevant difference between them. Let´s go to another example:

In the above example the values of the input or output parameters do not matter, so we’ll focus on the execution flow. Basically, the object f1 was created with the purpose of printing the word main on the console, but I’ve decided to add other functionalities by using Decorator Pattern, for that I’ve used the compose and andThen methods. Lastly, the apply method was invoked to execute all the accumulated functionalities.


compose 4
compose 3
compose 2
compose 1
andThen 1
andThen 2
andThen 3
andThen 4

As you can see, the execution order was not the same as that of the code declaration. That has happened because those two methods added its logic to different positions in the execution flow. The picture below explains it better:

Therefore, when we need to use Decorator Pattern in Function interface to accumulate functionalities, we can use those two methods. However, we need to be sure which execution order we need.

  • compose: The functionality will be added to be executed in the first position of the execution flow.
  • andThen: The functionality will be added to be executed in the last position of the execution flow.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store