Menu Bar

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Thursday, 29 December 2016

What is Functional Interface In Java ?


Functional Interface :

It belongs to java.util.function; package functional interface is defined as an interface with exactly one abstract method ,some functional interfaces are :
  1. Function<T,R> - takes an object of type T and returns R.
  2. Supplier<T> - just returns an object of type T.
  3. Predicate<T> - returns a boolean value based on input of type T.
  4. Consumer<T> - performs an action with given object of type T.
  5. BiFunction - like Function but with two parameters.
  6. BiConsumer - like Consumer but with two parameters. 
It also have some  interfaces for primitive data type :
  1. IntConsumer
  2. IntFunction<R>
  3. IntPredicate
  4. IntSupplier 

Example Showing Functional Interface:

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

public class FunctionalInterfaces {

public static void main(String[] args) {

List<Integer> list = Arrays.asList(1,2,5,8,3,6,9);
System.out.println("USE OF CUNSUMER INTERFACE TO TRAVERSE LIST");
list.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer t) {
System.out.println(t);
}
});

System.out.println("\nEVEN NUMBERS FROM LIST");
Predicate<Integer> predicate = n-> n%2 == 0;
list.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer t) {
if(predicate.test(t)){
System.out.println(t);
}
}
});

System.out.println("\nODD NUMBERS FROM LIST");
Predicate<Integer> oddPre = n-> n%2 != 0;
list.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer t) {
if(oddPre.test(t)){
System.out.println(t);
}
}
});
System.out.println("\nNUMBERS GREATER THAN 3 IN LIST");
Predicate<Integer> pre1 = n -> n>3;
list.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer t) {
if(pre1.test(t)){
System.out.println(t);
}
}
});
}
}
Program Output :

USE OF CUNSUMER INTERFACE TO TRAVERSE LIST
1
2
5
8
3
6
9

EVEN NUMBERS FROM LIST
2
8
6

ODD NUMBERS FROM LIST
1
5
3
9

NUMBERS GREATER THAN 3 IN LIST
5
8
6
9




                                                   
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



Share this Blog with yours Friends !!

No comments:

Post a Comment