Java Reference
In-Depth Information
The output is shown here:
In the program, the generic functional interface
SomeTest
is declared as shown here:
Here,
T
specifies the type of both parameters for
test( )
. This means that it is compatible
with any lambda expression that takes two parameters of the same type and returns a
boolean
result.
The
SomeTest
interface is used to provide a reference to three different types of
lambdas. The first uses type
Integer
, the second uses type
Double
, and the third uses type
String
. Thus, the same functional interface can be used to refer to the
isFactor
,
isFactorD
,
and
isIn
lambdas. Only the type argument passed to
SomeTest
differs.
As a point of interest, the
NumericFunc
interface shown in the previous section can also
be rewritten as a generic interface. This is an exercise in “
Chapter 14
Self Test,” at the end
of this chapter.
Try This 14-1
Pass a Lambda Expression as an Argument
A lambda expression can be used in any context that provides a target type. The target
contexts used by the preceding examples are assignment and initialization. Another one is
when a lambda expression is passed as an argument. In fact, passing a lambda expression
as an argument is a common use of lambdas. Moreover, it is a very powerful use because it