Use Function and BiFunction Interfaces in Lambda Expression in Java



The Function interface is a pre-defined functional interface that can be used as an assignment target for a lambda expression or method reference. It takes a single parameter and returns result by calling the apply() method. While the BiFunction interface is also a pre-defined functional interface that takes two parameters and returns a result. It is similar to the Function interface except it takes two parameters.

Syntax

@FunctionalInterface
public interface Function<T, R>

@FunctionalInterface
public interface BiFunction<T, U, R>

Example

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

public class SampleFunctionBiFunctionTest {
   public static void main(String[] args) {
      Function<Integer, Integer> printNumber = a -> a*10;
      System.out.println("The number is: "+ printNumber.apply(10));

      BiFunction<Integer, Integer, Integer> add = (a, b) -> a+b;
      System.out.println("The addition of two numbers are: "+ add.apply(3,2));
   }
}

Output

The number is: 100
The addition of two numbers are: 5
Updated on: 2020-07-13T06:37:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements