#
Composing Functions
This tutorial explains to you how we can compose functions in Java.
The "functions" are implementations of the Functions<T,R>
functional interfaces.
In my example, I start from a simple Spring Boot application created using Spring initializr.
Let's have the following functions:
f:Z -> Z, f(x) = x + 1
g:Z -> Z, g(x) = 2 * x
Info
- Z stands for integers, including all negative and positive integers.
f:Z -> Z
means that the function takes as parameter an integer and return an integer.
In the following example we will create another 2 functions:
h1:Z -> Z, h1(x) = g(f(x)) = (g o f)(x) --> f.andThen(g);
h2:Z -> Z, h2(x) = f(g(x)) = (f o g)(x) --> f.compose(g)
Here is the Java code for testing the situation above:
package com.exampe.java;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.function.Function;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
System.out.println("--------------------------------------------");
Function<Integer, Integer> f = x -> x + 1;
Function<Integer, Integer> g = x -> 2 * x;
// f(x) is calculated and will be the input parameter for g(x) || h1(x) = g(f(x))
Function<Integer, Integer> h1 = f.andThen(g);
Integer result1 = h1.apply(2);
System.out.println("Result1 = "+result1);
// g(x) is calculated and will be the input parameter for f(x) || h2(x) = f(g(x))
Function<Integer, Integer> h2 = f.compose(g);
Integer result2 = h2.apply(2);
System.out.println("Result2 = "+result2);
System.out.println("--------------------------------------------");
System.out.println("End of the execution");
}
}
When we run the application we can see:
--------------------------------------------
Result1 = 6
Result2 = 5
--------------------------------------------
End of the execution
Please take a look at the comments in the code.
Info
We can create transformation pipelines using functions and andThen or compose methods.