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

No comments:
Post a Comment