Java Reference
In-Depth Information
Chapter 2
Understanding Lambdas in Java 8
The core new functionality in Java 8 is the introduction of lambdas. However, most introductions will show a
couple of examples of lambdas, and then they leave it to the developer to figure out the rest. If you are going
to be developing modern Java programs, however, you are going to need to be well versed in how lambdas
can be used. Throughout this chapter, we will dig into the particularities of the syntax and semantics of
lambdas, including how to create more complex lambdas, how to work with method calls and lambdas, and
what this all looks like under the hood. We will also look at some classic ways to manipulate lambdas, and
how they are implemented within Java. By the end of this chapter, you should be fluent in how to create the
lambdas that you want.
While I promise that this chapter is very concrete, its purpose is to present the syntax and semantics
of lambdas. In order to maintain the clarity and precision of the examples, we will present them without
creating a context for their application. If your inner schoolchild begins saying, “Yeah, but when are you ever
going to use this?” then please feel free to peruse the practical examples throughout every other chapter of
this topic. Here, the goal is to become a technical expert on lambdas, method references, and the functional
interfaces that support them. With that grounding, we can move into the more interesting and complex cases
in the rest of the topic.
Java 8's Lambda Syntax
The simplest lambda is one that takes a single argument and returns that argument, and we have a method
that generates that lambda in Listing 2-1. It is easiest to understand that method if we work from the outside
in. Let's start with the signature: the method is named identityFunction , and it will return a Function .
The Function type is a new interface in Java 8, part of the java.util.function package, and that interface
represents a single-argument lambda with a return value. Our returned Function takes an object of variable
type V and provides an object of the same type, so the type is <V, V>. A different function might take one type
and return another; a function might take any object and return a String, for instance. In that case, its type
would be <Object,String>. But the types are the same here: the return value is the same as the argument.
Moving into the body of the method itself, we have a return statement. That return statement returns a
lambda, and that lambda is the implementation for our Function interface. The lambda takes a single
argument named value on the left side of the arrow, and it returns value on the right side of the arrow.
Listing 2-1. Identity Function Implemented Using a Lambda
public static <V> Function<V, V> identityFunction() {
return value -> value;
Search WWH ::

Custom Search