Functional Interfaces
A functional interface in Java is an interface that contains only a single abstract method.
It can have any number of default, static methods.
It is also called SAM(Single Abstract Method) Interfaces.
A functional interfaces can be created with lambda expressions, method references, or constructor references.
Functional Interface can't have multiple abstract methods and so that if interface have @FunctionalInterface Annotation that indicating, it should not have more than one abstract method than the compiler will gives flags an ‘Unexpected @FunctionalInterface annotation’ message.
A Functional Interfaces can be implemented by a Lambda Expression.
All the built in Functional Interfaces are defined in import java.util.function.*; package
The use of @this annotation is optional.
Some of the Functional Interfaces are Runnable, Comparable, ActionListener, Callable
Program of user defined Functional Interface
@FunctionalInterface
interface Sum
{
int sumCalculation(int a, int b);
}
public class ExampleOfFunctionalInterfaceAnnotation
{
public static void main(String[] args)
{
int m=10; int n=20;
Sum sum=(int a, int b)->a+b; // lambda expression to define the calculate method
int result=sum.sumCalculation(m, n); // parameter passed and return type must be same
System.out.println("Result: "+result);
}
}
Built in Functional Interfaces
Function
The Function interface has an abstract method apply which takes argument of type T and returns a result of type R.
Syntax is:-
import java.util.function.Function;
public interface Function
{
public R apply(T t);
}
Program to find length of string is:-
import java.util.function.Function;
public class Fun
{
public static void main(String[] args)
{
Function<String, Integer> obj = x -> x.length();
Integer test = obj.test("Love"); // 4
System.out.println(test);
}
}
Predicate
The Predicate interface has an abstract method test which gives a Boolean value as a result for the specified argument.
Syntax is:-
import java.util.function.Predicate;
public interface Predicate
{
public boolean test(T t);
}
Program is:-
import java.util.*;
import java.util.function.Predicate;
//A simple program to demonstrate the use of predicate interface
public class Java8functionPackage
{
public static void main(String[] args)
{
// creating a list of type strings
List<String> names = Arrays.asList("Nagendra","Navneet","Heera","Hero","Narvdesh");
// declaring the string type predicate, using lambda expression to create object predicate
Predicate<String> predicate = (s)->s.startsWith("N");
// Iterate through the list
for (String str:names)
{
// call the test method of Predicate that have return type Boolean
if (predicate.test(str))
System.out.println(str);
}
}
}