Java 8 BiFunction Example

In this tutorial, we will learn how to use Java 8 BiFunction interface with an example.
The BiFunction interface is a functional interface introduced in Java 8 and we use the lambda expression to implement Java 8 BiFunction interface.
Learn functional interfaces at https://www.javaguides.net/2018/07/java-8-functional-interfaces.html
Learn lambda expressions at https://www.javaguides.net/2018/07/java-8-lambda-expressions.html.

Video

Java 8 BiFunction Interface Overview

This interface represents a function that takes two arguments of different types and produces a result of another type. 
This how the interface is defined:
@FunctionalInterface
public interface BiFunction<T, U, R> {
     R apply(T t, U u); // Other default and static methods
     // ...
}

Java 8 - BiFunction Example #1

Note the comments are self-descriptive.
package com.javaguides.java.functionalinterfaces;

import java.util.function.BiFunction;
import java.util.function.Function;

public class BiFunctionDemo {

    public static void main(String[] args) {

        // Here's an example using an anonymous class:
        BiFunction < Integer, Integer, Integer > biFunctionObj = new BiFunction < Integer, Integer, Integer > () {

            @Override
            public Integer apply(Integer t, Integer u) {
                return (t + u);
            }
        };

        System.out.println(biFunctionObj.apply(10, 20));

        // And with a lambda expression:
        BiFunction < Integer, Integer, Integer > biFunction = (t, u) - > (t + u);

        BiFunction < Integer, Integer, Integer > substraction = (t, u) - > (t - u);

        BiFunction < Integer, Integer, Integer > multiplication = (t, u) - > (t * u);

        BiFunction < Integer, Integer, Integer > division = (t, u) - > (t / u);

        Function < Integer, Integer > function = (number) - > number * number;
        Integer integer = biFunction.andThen(function).apply(10, 20);
        System.out.println(integer);

        System.out.println(biFunction.apply(10, 20));
        System.out.println(substraction.apply(200, 100));

        System.out.println(multiplication.apply(200, 100));

        System.out.println(division.apply(200, 100));
    }

}
Output:
30
900
30
100
20000
2

Java 8 - BiFunction Example #2

The following example shows how to use the default method andThen() of the BiFunction interface with a lambda expression.
package com.javaguides.java.functionalinterfaces;

import java.util.function.BiFunction;
import java.util.function.Function;

public class BiFunctionDemo {

    public static void main(String[] args) {

        BiFunction < Integer, Integer, Integer > function1 = (a, b) - > a + b;
        Function < Integer, Integer > function2 = (n) - > n * n;

        //Using andThen()
        System.out.println(function1.andThen(function2).apply(2, 3));
        System.out.println(function1.andThen(function2).apply(4, 5));
    }

}
Output:
25
81

Related Java 8 Tutorials:

Comments