What is the generic functional interface in Java?

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 24-Dec-2019 12:17:36
Advertisements