JAVA 8 FUNTIONAL INTERFACE
Funtional Interface :
An interface which has only one abstract method can be called a funtional interface.
Comparable , Runnable , Callable all these interfaces has only one abstract method and can be consider as funtional interface.
How it works :
Once we will create a interface with one abstract method then java internally predicates the input type and based on the Interface reference it apply the logic mentioned after lambda expression
lets consider we have created an interface as below
@FunctionalInterface
public interface FuntionalExample {
public int cal(int a, int b);
}
And below class to test our funtional Interface.
public class FuntionalInterfaceExample {
public static void main(String args[])
{
FuntionalExample addition=(int a, int b) -> a+b;
FuntionalExample subtraction=(int a, int b) -> a-b;
FuntionalExample multiplication=(int a, int b) -> a*b;
FuntionalExample division=(int a, int b) -> a/b;
System.out.println(addition.cal(10,5));
System.out.println(subtraction.cal(10,5));
System.out.println(multiplication.cal(10,5));
System.out.println(division.cal(10,5));
}
}
Output is as below :
15
5
50
2
Here if you noticed we have created instances of funtional Interface but the logic after lambda expression has been changed and whenever i am using addition reference to call cal(int a , int b) method its doing addition because after lambda we did a+b while for subtraction it's a-b , for multiplication it's a*b while for division it's a/b.
JAVA 8 FUNTIONAL INERFACES :
There are 3 new java functional interafce has been introduced to help in stream api.
1) Consumer is a funtional interface with only one abstract method void accept(T t), with no return type and an input param of type T. In below code snippet we have created reference of Consumer as per our code choice and using it in stream of String.
Consumer<String> printc=c -> {System.out.println("City name :"+c);};
Stream<String> cities=Stream.of("Pune","Kolkata","Bangalore","Mumbai");
cities.forEach(printc);
Output :
City name :Pune
City name :Kolkata
City name :Bangalore
City name :Mumbai
2) Supplier is another funtional interface with only abstract method T get(T t), takes an input of Type T and return same type or orElseReturn with default values set.
Stream<String> cities=Stream.of("Pune","Kolkata","Bangalore","Mumbai");
cities.filter(c -> c.startsWith("A")).forEach(s -> System.out.println(s)).orElseReturn(supplier);
Output : No values found
3) Predicate is another funtional interface with only abstract method boolean Test(T t), takes an input of Type T and return a boolean type either TRUE or FALSE.
Stream<String> cities=Stream.of("Pune","Kolkata","Bangalore","Mumbai");
Predicate<String> predicate=s -> s.startsWith("P");
cities.filter(predicate).forEach(System.out::println);
Output : Pune
Comments
Post a Comment