Composing Functions with compose() andThen()

As we already saw in a previous article, the  java.util.Function interface represents a function that accepts one argument and produces a result. In this article, let us see how we can compose a function from two others.

Using compose()

The compose() method is a default method in the Function interface that returns a composed function that first applies the before function to its input, and then applies this function to the result.

Here is an example.

Function<Integer, Integer> before = x -> x + 10;
Function<Integer, Integer> after = x -> x * 2;
Function<Integer, Integer> combined = after.compose(before);
System.out.println(combined.apply(5)); // Prints 30

In the above example, the before function runs first, adding 10 to 5 and the resulting 15 is multiplied by 2 when the after function runs. Thus the output is 30.

Using andThen()

The andThen() method is also a default method in the Function Interface, which works in the opposite manner to compose(). This means that calling b.compose(a) is actually the same as calling a.andThen(b).

This method returns a composed function that first applies this function to its input, and then applies the after function to the result..

Let us understand with the below example.

Function<Integer, Integer> before = x -> x + 10;
Function<Integer, Integer> after = x -> x * 2;
Function<Integer, Integer> combined = before.andThen(after);
System.out.println(combined.apply(5));

Quiz

Click here to attempt quiz questions on this topic.

Leave a Reply

Your email address will not be published. Required fields are marked *