Java Reference
In-Depth Information
then the following creates a constructor reference with a type argument of
Integer
:
Because of type inference, you won't always need to specify the type argument, but you
can when necessary.
Predefined Functional Interfaces
Up to this point, the examples in this chapter have defined their own functional interfaces
so that the fundamental concepts behind lambda expressions and functional interfaces
could be clearly illustrated. In many cases, however, you won't need to define your own
functional interface because JDK 8 adds a new package called
java.util.function
that
provides several predefined ones. Here is a sampling:
Interface Purpose
UnaryOperator<T>
Apply a unary operation to an object of type
T
and return the result,
which is also of type
T
. Its method is called
apply( )
.
BinaryOperator<T>
Apply an operation to two objects of type
T
and return the result,
which is also of type
T
. Its method is called
apply( )
.
Apply an operation on an object of type
T
. Its method is called
ac-
cept( )
.
Consumer<T>
Supplier<T>
Return an object of type
T
. Its method is called
get( )
.
Apply an operation to an object of type
T
and return the result as an
object of type
R
. Its method is called
apply( )
.
Function<T, R>
Determine if an object of type
T
fulfills some constraint. Returns a
boolean
value that indicates the outcome. Its method is called
test(
)
.
Predicate<T>
The following program shows the
Predicate
interface in action. It uses
Predicate
as the
functional interface for a lambda expression the determines if a number is even.
Predic-
ate
's abstract method is called
test( )
, and it is shown here:
boolean test(T
val
)