What is the generic functional interface in Java?


A lambda expression can't specify type parameters, so it's not generic. However, a functional interface associated with lambda expression is generic. In this case, the target type of lambda expression has determined by the type of argument(s) specified when a functional interface reference is declared.

Syntax

interface SomeFunc {
 T func(T t);
}

Example

interface MyGeneric<T> {
   T compute(T t);
}
public class LambdaGenericFuncInterfaceTest {
   public static void main(String args[]) {
      MyGeneric<String> reverse = (str) -> {   // Lambda Expression
         String result = "";
         for(int i = str.length()-1; i >= 0; i--)
            result += str.charAt(i);
         return result;
         };
      MyGeneric<Integer> factorial = (Integer n) -> {   // Lambda Expression
         int result = 1;
         for(int i=1; i <= n; i++)
            result = i * result;
         return result;
      };
      System.out.println(reverse.compute("Lambda Generic Functional Interface"));
      System.out.println(factorial.compute(7));
   }
}

Output

ecafretnI lanoitcnuF cireneG adbmaL
5040

Updated on: 11-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements