Functions

Java Joy: Composing Functions

Posted on by  
Hubert Klein Ikkink

In Java we can write single argument functions that implement the java.util.function.Function interface. We can combine multiple functions into a new function using the andThen and compose methods from the Function interface. We need to give another function as argument to these methods. When we use the andThen method the output of the original function will be input of the function passed as argument. With the compose method our function will get as input the output of the function that is passed as argument. It is important to know the difference, because it can change the result of the function we are composing. The andThen and compose methods are also available on the IntUnaryOperator, LongUnaryOperator and DoubleUnaryOperator interface.

In the following example we use both andThen and compose to chain together some functions. We can see the result can be different when using andThen and compose with the same functions.

Continue reading →

shadow-left