We can combine BiFunction and Function in a pipeline using andThen method.
In the below example we have BiFunction which returns the product of 2 numbers.
Output of BiFunction is fed to Function using andThen method.
Function transform the input given into customised output.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
packagecom.examples;importjava.util.List;importjava.util.function.BiFunction;importjava.util.function.Function;publicclassApp{publicstaticvoidmain(String[]args){BiFunction<Integer,Integer,Integer>add=(x,y)->x*y;Function<Integer,String>output=(x)->"Product is "+x;Stringresult=add.andThen(output).apply(5,10);System.out.println(result);// Product is 50
}}
Let us take one more use case.
In the below example we concatenate 2 strings using BiFunction and convert them to uppercase using Function
as shown below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
packagecom.examples;importjava.util.List;importjava.util.function.BiFunction;importjava.util.function.Function;publicclassApp{publicstaticvoidmain(String[]args){BiFunction<String,String,String>add=(x,y)->x.concat(y);Function<String,String>output=x->x.toUpperCase();Stringresult=add.andThen(output).apply("This is ","new code");System.out.println(result);// THIS IS NEW CODE
}}
Conclusion
BiFunction is similar to Function but it takes 2 arguments. We can compose BiFunction together with Function which gives much flexibility
to perform business on the data as it is processed.
Hope this clarifies how to use BiFunction in our code.