Java 8 BiFunction Examples

Java 8 BiFunction

BiFunction is a functional interface introduced in Java 8.BiFunction interface’s method takes two parameter (T and U ) and returns one parameter(R) as output.

Syntax:

@FunctionalInterface
public interface BiFunction {
      R apply(T t, U u);
}

T: Type of the first argument to the function
U: Type of the second argument to the function

R: Type of the result returned from the function

Example

 // BiFunction to sum 2 integer numbers and returing result of type integer
    BiFunction sum = (firstArg, secondArg) -> firstArg + secondArg;
    // Implementing BiFunctin sum using apply() method
    System.out.println("Sum = " + sum.apply(2, 3));    

Example 2

  // BiFunction to sum 2 integer numbers and returing result of type List of integers
    BiFunction> biFunctionReturningList = (firstArg, secondArg) -> Arrays.asList(firstArg + secondArg);
    // Implementing BiFunctin sum using apply() method
    List resultList = biFunctionReturningList.apply(2, 3);
    System.out.println("BiFunctionReturningList = " + resultList);    

Function Composition:
Function interface has some methods which can be used to compose new function instances from existing instances.


2) addThen()


It returns a composed function wherein the parameterized function will be executed after the first one.
functionA.andThen(functionB) will first apply functionA to the input and then result of this will be passed to the functionB.

Syntax:
default  
    BiFunction 
        addThen(Function after)  

Example:

 // BiFunction Composite functions
    // Here it will calculate the sum of two integers 12 and 13
    // and then multiply it by 2 and then returns the results
    BiFunction compositeBiFunction = (a, b) -> a + b;
    // Using addThen() method
    compositeBiFunction = compositeBiFunction.andThen(a -> 2 * a);
    System.out.println("Composite BiFunction = " + compositeBiFunction.apply(12, 13));     

Leave a comment