Java Joy: Composing Functions
A quick look at composing and chaining functions.
Join the DZone community and get the full member experience.Join For Free
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
compose methods from the
Function interface. We need to give another function as an argument to these methods. When we use the
andThen method the output of the original function will be an input of the function passed as an argument. With the
compose method our function will get as input the output of the function that is passed as an argument. It is important to know the difference because it can change the result of the function we are composing. The
compose methods are also available on the
In the following example, we use both
compose to chain together some functions. We can see the result can be different when using
compose with the same functions.
Written with Java 15.
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.