Java BiFunction and Function example

March 11, 2020 | No comments

Bifunction - Introduction

Java 8 Introduced many utility interfaces for functional programming. Function and BiFunction are two of those. Following article explores how we can use Function and BiFunction interfaces, specially the methods apply and andThen.

Function Interface

Function
Function interface It provides following important methods like apply.
public interface Function 
R apply(T t);
default  Function andThen(Function after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }

BiFunction Interface

BiFunction
BiFunction interface It provides following important methods like apply, andThen
public interface BiFunction
 R apply(T t, U u);
 default  BiFunction andThen(Function after) {
        Objects.requireNonNull(after);
        return (T t, U u) -> after.apply(apply(t, u));
 }

BiFunction and Function Example

Java8BiFunction.java
public class Java8BiFunction {

  public void BiFunctionExample() {

    // Bifunction to adds two numbers
    BiFunction<Integer, Integer, Integer> addBiFunction = (a, b) -> a + b;

    // Prints 3
    System.out.println("Add BiFunction " + addBiFunction.apply(1, 2));

    // Prints 33
    System.out.println("Add BiFunction " + addBiFunction.apply(11, 22));
  }

  public void BiFunctionAndThenExample() {

    // Bifunction to multiply two numbers
    BiFunction<Integer, Integer, Integer> multiplyBiFn = (a, b) -> a * b;

    // Function to increment value by 1
    Function<Integer, Integer> incrementFn = (a) -> a + 1;


    // Prints 4
    System.out.println("BiFunctionAndThen BiFunction "
        + multiplyBiFn.andThen(incrementFn).andThen(incrementFn).apply(2, 1));

    // Prints 32
    System.out.println("BiFunctionAndThen BiFunction "
        + multiplyBiFn.andThen(incrementFn).andThen(incrementFn).apply(5, 6));
  }
}
Note
  • apply method applies the argument to the function
  • andThen can be used to chain function calls
  • andThen is called on the result returned by apply call
  • BiFunction:: apply takes two function arguments
  • Function::apply takes single function argument

No comments :

Post a Comment

Please leave your message queries or suggetions.