How to implement Function interface with lambda expression in Java?


Function<T, R> interface is a functional interface from java.util.function package. This interface expects one argument as input and produces a result. Function<T, R> interface can be used as an assignment target for a lambda expression or method reference. It contains one abstract method: apply(), two default methods: andThen() and compose() and one static method: identity().

Syntax

@FunctionalInterface
public interface Function<T, R> {
 R apply(T t);
}

Example

import java.util.function.Function;

public class FunctionTest {
   public static void main(String[] args) {
      Function<Integer, Integer> f1 = i -> i*4;   // lambda
      System.out.println(f1.apply(3));

      Function<Integer, Integer> f2 = i -> i+4; // lambda
      System.out.println(f2.apply(3));

      Function<String, Integer> f3 = s -> s.length(); // lambda
      System.out.println(f3.apply("Adithya"));

      System.out.println(f2.compose(f1).apply(3));
      System.out.println(f2.andThen(f1).apply(3));

      System.out.println(Function.identity().apply(10));
      System.out.println(Function.identity().apply("Adithya"));
   }
}

Output

12
7
7
16
28
10
Adithya

Updated on: 14-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements