The above are Functional Interfaces added in Java 8 and beyond. There are more than 40 Functional Interfaces in java, but here we will talk about only 4 important ones- Predicate, Function, Consumer and Supplier.
Predicate
It is a functional interface that is used to test a condition. Predicate accept only one argument and return a boolean value. For e.g. the signature of filter method is something like this: filter(Predicate predicate)
The source code of Predicate Functional Interface would look something like this:
@FunctionalInterface public interface Predicate<T> { boolean test(T t); //It also contains some other default and static methods. }
Lets see the below code snippet:
Predicate<Integer> predicate= x -> x % 2 == 0; System.out.println(predicate.test(5));
The output:
false
Usage in filter(Predicate) method:
.filter(x -> x%2 == 0)
Function
Function interface is used to do the transformation. It can accepts one argument and produces a result. For eg., map(Function function)
The source code of Function Functional Interface would look something like this:
@FunctionalInterface public interface Function<T, R> { R apply(T t); //It also contains some other default and static methods. }
Lets see the below code snippet:
Function<Integer,Integer> function= x -> x * x; System.out.println(function.apply(5));
The output:
25
Usage in map(Function) method:
.map(x -> x*x)
Consumer
It represents an operation that accepts a single input argument and returns no result. For eg., the method: forEach(Consumer consumer)
The source code of Consumer Functional Interface would look something like this:
@FunctionalInterface public interface Consumer<T> { void accept(T t); //It also contains some other default and static methods. }
Lets see the below code snippet:
Consumer<Integer> consumer = x -> System.out.println(x); consumer.accept(5);
The output:
5
Usage in forEach(Consumer) method:
.forEach(x -> System.out.println(x));
Supplier:
Supplier
is a functional interface that takes no inputs and returns a result. The results produced each time can be the same or different. The interface contains one method, get
():
@FunctionalInterface public interface Supplier<T> { /** * Gets a result. * * @return a result */ T get(); }
Usage in Java:
int max=intList.stream().max((x,y) -> x - y).get();
The above are some of the Functional Interfaces added in java 8.
In Java, an object is the thing which is being passed across other entities – methods, variables, etc.. So an object is the first class citizen in java. But in Python a function is a first class citizen, everything there is build across function. Java introduced this functional programming into it very late since it does not want to break any application developed from its old version.