Java Reference
In-Depth Information
Know about the predefined functional interfaces in java.util.function
W ith the release of JDK 8, a new feature has been added to Java that profoundly enhances
the expressive power of the language. This feature is the lambda expression . Not only do
lambda expressions add new syntax elements to the language, they also streamline the way
that certain common constructs are implemented. In much the same way that the addition
of generics reshaped Java years ago, lambda expressions are reshaping Java today. They
truly are that important.
The addition of lambda expressions have also provided the catalyst for other new Java
features. You have already seen one of them—the default method—which was described
in Chapter 8 . It lets you define default behavior for an interface method. Another example
is the method reference, described later in this chapter, which lets you refer to a method
without executing it. Furthermore, the inclusion of lambda expressions resulted in new cap-
abilities being incorporated into the API library.
Beyond the benefits that lambda expressions bring to the language, there is another reas-
on why they constitute such an important addition to Java. Over the past few years, lambda
expressions have become a major focus of computer language design. For example, they
have been added to languages such as C# and C++. Their inclusion in Java helps it re-
main the vibrant, innovative language that programmers have come to expect. This chapter
presents an introduction to this exciting new feature.
Introducing Lambda Expressions
Key to understanding the lambda expression are two constructs. The first is the lambda ex-
pression, itself. The second is the functional interface. Let's begin with a simple definition
of each.
A lambda expression is, essentially, an anonymous (that is, unnamed) method. However,
this method is not executed on its own. Instead, it is used to implement a method defined
by a functional interface. Thus, a lambda expression results in a form of anonymous class.
Lambda expressions are also commonly referred to as closures .
A functional interface is an interface that contains one and only one abstract method.
Normally, this method specifies the intended purpose of the interface. Thus, a functional
interface typically represents a single action. For example, the standard interface Runnable
is a functional interface because it defines only one method: run( ) . Therefore, run( )
defines the action of Runnable . Furthermore, a functional interface defines the target type
of a lambda expression. Here is a key point: a lambda expression can be used only in a con-
Search WWH ::




Custom Search