Functional Interface
Functional interface is an interface having exactly one abstract method
called functional method to which the lambda expression’s parameter and return types are matched.
Functional interface provides target types for lambda expressions and method references.
Functional Interface rules
As discussed
@FunctionalInterface
is a runtime annotation
that is used to verify the interface follows all the rules
that can make this interface as functional interface.
- Interface must have exactly one
abstract method
. - It can hava any number of
default methods
because they are not abstract and implementation is already provided by
same. - Interface can declare an abstract method
overriding
one of the public method fromjava.lang.Object
,
that still can be considered as functional interface.
The reason is any implementation class to this interface will have implementation for this abstract methodeither
from super class(java.lang.Object)or
defined by implementation class itself.
1 |
|
Predicate
java.util.function.Predicate
has a boolean-valued function that takes an argument and return boolean value.
1 | public interface Predicate<T>{ |
Example
1 | import java.util.ArrayList; |
Output
1 | Odds:[-9, -7, -5, -3, -1, 1, 3, 5, 7, 9] |
Method | Description | Example |
---|---|---|
and(Predicate<? super T> other | Returns a composite predicate that represents logical` of two predicates(p1 AND p2) | Predicate |
or(Predicate<? super T> other) | Returns a composite predicate that represents logical OR of two predicates(p1 OR p2) |
Predicate |
negate() | Returns a composite predicate that represents logical negation of this predicate |
Predicate |
Consumer
java.util.Consumer
accepts an argument and returns no result.
1 | public interface Consumer<T>{ |
Example
1 | import java.util.ArrayList; |
Output
1 | 10 |
Consumer has also one default method called
andThen(Consumer<? super T> after
which returns a composite consumer where second consumer will be executed after execution of first one.
If the first consumerthrows any exception
then the second consumer willnot be executed
.
Supplier
java.util.function.Supplier
doesn’t accept any argument but returns a result.
1 | public interface Supplier<R>{ |
Example
1 | import java.util.Random; |
Function<T, R>
java.util.function.Function
accepts an argument and return result.
1 | public interface Function<T, R>{ |
Example
1 | import java.util.function.Function; |
Output
1 | value:260.0,type:class java.lang.Double |
Method | Description |
---|---|
default |
Returns a composed function that first applies the before function to its input ,and then applies this function to the result |
default |
Returns a compose function that first applies this function to its input,and then applies the after function to the result |
static |
Returns a function that always return its input argument.Basically it is a helper method that used in Collector implementation |