Java Reference
In-Depth Information
tion<T,R> contains an abstract method declaration of apply() . To invoke this
lambda expression, use the following syntax:
System.out.println(newText2.apply("WORLD"));
Result:
DLROW
How It Works
A basic building block of a lambda expression is the functional interface. A functional
interface is a standard Java interface that contains only one abstract method declaration
and provides a target type for lambda expressions and method references. A functional
interface may contain default method implementations as well, but only one abstract
declaration. The abstract method is then implicitly implemented by the lambda expres-
sion. As a result, the lambda expression can be assigned to a variable of the same type
as the functional interface. The method can be called upon from the assigned variable
at a later time, thus invoking the lambda expression. Following this pattern, lambda ex-
pressions are method implementations that can be invoked by name. They can also be
passed as arguments to other methods (see Recipe 6-8).
Note The functional interface in solution 1 contains the @FunctionalInter-
face annotation. This can be placed on a functional interface to catch compiler-level
errors, but it has no effect on the interface itself.
At this point you may be wondering if you will be required to develop a functional
interface for each situation that may be suitable for use with a lambda expression. This
is not the case, as there are many functional interfaces already in existence. Some ex-
amples include java.lang.Runnable , javafx.event.EventHandler , and
java.util.Comparator . See some of the other recipes in this chapter for ex-
amples using lambda expressions that implement these interfaces. However, there are
also many more functional interfaces that are less specific, enabling them to be tailored
to suit the needs of a particular requirement. The java.util.function package
contains a number of functional interfaces that can be useful when implementing
lambda expressions. The functional interfaces contained within the package are utilized
throughout the JDK, and they can also be utilized in developer applications. Table 6-1
 
Search WWH ::




Custom Search