Java Reference
In-Depth Information
Interface
Description
BinaryOperator<T>
Contains method
apply
that takes two
T
arguments, performs an operation
on them (such as a calculation) and returns a value of type
T
. You'll see several
examples of
BinaryOperator
s starting in Section 17.3.
Consumer<T>
Contains method
accept
that takes a
T
argument and returns
void
. Performs
a task with it's
T
argument, such as outputting the object, invoking a method
of the object, etc. You'll see several examples of
Consumer
s starting in
Section 17.3.
Function<T,R>
Contains method
apply
that takes a
T
argument and returns a value of type
R
. Calls a method on the
T
argument and returns that method's result. You'll
see several examples of
Function
s starting in Section 17.5.
Predicate<T>
Contains method
test
that takes a
T
argument and returns a
boolean
. Tests
whether the
T
argument satisfies a condition. You'll see several examples of
Predicate
s starting in Section 17.3.
Supplier<T>
Contains method
get
that takes no arguments and produces a value of type
T
. Often used to create a collection object in which a stream operation's
results are placed. You'll see several examples of
Supplier
s starting in
Section 17.7.
UnaryOperator<T>
Contains method
get
that takes no arguments and returns a value of type
T
.
You'll see several examples of
UnaryOperator
s starting in Section 17.3.
Fig. 17.2
|
The six basic generic functional interfaces in package
java.util.function
.
Functional programming is accomplished with lambda expressions. A
lambda expression
represents an
anonymous method
—a shorthand notation for implementing a functional in-
terface, similar to an anonymous inner class (Section 12.11). The type of a lambda expres-
sion is the type of the functional interface that the lambda expression implements. Lambda
expressions can be used anywhere functional interfaces are expected. From this point for-
ward, we'll refer to lambda expressions simply as lambdas. We show basic lambda syntax
in this section and discuss additional lambda features as we use them throughout this and
later chapters.
Lambda Syntax
A lambda consists of a
parameter list
followed by the
arrow token (
->
)
and a body, as in:
(
parameterList
) -> {
statements
}
The following lambda receives two
int
s and returns their sum:
(
int
x,
int
y) -> {
return
x + y;}
In this case, the body is a
statement block
that may contain
one or more
statements enclosed
in curly braces. There are several variations of this syntax. For example, the parameter
types usually may be omitted, as in:
(x, y) -> {
return
x + y;}