Java Reference
In-Depth Information
Chapter 3. Lambda expressions
This chapter covers
Lambdas in a nutshell
Where and how to use lambdas
The execute around pattern
Functional interfaces, type inference
Method references
Composing lambdas
In the previous chapter, you saw that passing code with behavior parameterization is useful for
coping with frequent requirement changes in your code. It lets you define a block of code that
represents a behavior and then pass it around. You can decide to run that block of code when a
certain event happens (for example, a click on a button) or at certain points in an algorithm (for
example, a predicate such as “only apples heavier than 150 g” in the filtering algorithm or the
customized comparison operation in sorting). In general, using this concept you can write code
that's more flexible and reusable.
But you saw that using anonymous classes to represent different behaviors is unsatisfying: it's
verbose, which doesn't encourage programmers to use behavior parameterization in practice. In
this chapter, we teach you about a new feature in Java 8 that tackles this problem: lambda
expressions, which let you represent a behavior or pass code in a concise way. For now you can
think of lambda expressions as anonymous functions, basically methods without declared
names, but which can also be passed as arguments to a method as you can with an anonymous
class.
We show how to construct them, where to use them, and how you can make your code more
concise by using them. We also explain some new goodies such as type inference and new
important interfaces available in the Java 8 API. Finally, we introduce method references, a
useful new feature that goes hand in hand with lambda expressions.
This chapter is organized in such a way as to teach you step by step how to write more concise
and flexible code. At the end of this chapter, we bring together all the concepts taught into a
concrete example: we take the sorting example shown in chapter 2 and gradually improve it
using lambda expressions and method references to make it more concise and readable. This
chapter is important in itself and also because you'll use lambdas extensively throughout the
book.
 
Search WWH ::




Custom Search