Sunteți pe pagina 1din 15

OCA Java SE 8 Programmer I Study Guide (Exa...

http://viewer.books24x7.com/AssetViewer.aspx?...

OCA Java SE 8 Programmer I Study Guide (Exam 1Z0-808)


Chapter 11 - Understanding Lambda Expressions
Oracle Press 2016

Chapter 11: Understanding Lambda Expressions


The lambda expressions feature is new in Java 8. This chapter shows you how to
write a simple lambda expression that uses the Predicate functional interface
(FI). Leading up to this coverage, FIs and lambda expressions syntax information is
provided and explained. The goal of the chapter is to help ensure that you have a
working knowledge of the related lambda expressions features that you may see on
the exam. Remember that by studying for a certification exam, you prove your
knowledge of a specific skill set such as using lambdas. So prior to reading this
chapter, you should already have a basic knowledge of lambda expressions. For
the scope of the exam, be prepared for questions on lambda expressions syntax,
passing lambda expressions through method arguments, and the typical use of the
Predicate interface.
Lambda expressions are considered a closure-like construct. These types of
constructs are presented in other languages as well, but with different names and
varying usages: C has callbacks and blocks, C++ has blocks and function objects,
Objective-C 2.0 has blocks; C# and D have delegates; Eiffel has inline agents.
Consider reviewing these closure-like constructs of the other programming
languages to get a better feel for the concept of closures.
Note that the general concept of closures, including lambda expressions, is the
ability to work with a function that can be stored as a variable (for example, a
first-class method). With this feature comes the ability to pass around the method (a
block of code).

CERTIFICATION OBJECTIVE: Write Lambda Expressions


Exam Objective Write a simple Lambda expression that consumes a Lambda
Predicate expression
Java lambda expressions provide a means to represent anonymous methods using
expressions. Lambda expressions provide coders with access to functional
programming capabilities in the object-oriented Java space. Lambda expressions
are supported by Project Lambda (http://openjdk.java.net/projects/lambda) and the
lambda expressions specification as presented in JSR 335 (http://jcp.org/en/jsr
/detail?id=335). The outline of JSR 335 includes nine parts, and if you are serious
about mastering lambda expressions, you should take the time to read through
each part. Part I is excluded from the specification.
q
q
q
q
q
q
q
q

1 of 15

Part A: Functional Interfaces


Part B: Lambda Expressions
Part C: Method References
Part D: Poly Expressions
Part E: Typing and Evaluation
Part F: Overload Resolution
Part G: Type Interference
Part H: Default Methods

13/10/2016 10:25

OCA Java SE 8 Programmer I Study Guide (Exa...

http://viewer.books24x7.com/AssetViewer.aspx?...

q Part J: Java Virtual Machine

In this chapter, the features of the first two parts of the specificationPart A:
Functional Interfaces and Part B: Lambda Expressionsare examined, as the
content of these parts are included on the exam. After reviewing Parts A and B of
the specification, a working example of lambda expressions and the Predicate FI
are presented.

Functional Programming
Functional programming is integrated with Java in Java SE 8. Lambda expressions
support functional programming in Java and add several benefits that software
developers can take advantage of, including ease of use, one of the most important
features. Lambdas in Java have long been awaited and their absence criticized.
They delightfully provide an alternative to the awkward and difficult-to-understand
anonymous inner classes that routinely challenge new developers. In addition to
ease of use, lambda expressions offer other values brought from the introduction of
functional programming:
q A clear and concise way to represent a method interface using an expression
q Code reduction, typically to a single line
q Improvement to the collections library (easier iteration, filtering, sorting, counting, data
extraction, and so on)
q Improvement to the concurrency library (improved performance in multicore environments)
q Lazy evaluation support through streams

There is a trade-off when implementing code with lambda expressions, however;


the debugging process is more complex because the call stacks can be
considerably longer. When you prefer finer levels of debugging, you may choose to
forgo the use of lambda expressions.
Heres an example of code that uses a lambda expression and an FI:

Larger View

To understand what is going on here, we need to visit functional interfaces.

Functional Interfaces
Lambda expressions must have a functional interface, also called a single abstract
method (SAM). FIs provide target types for lambda expressions as well as method
references. FIs must also have exactly one abstract method. Because the name of
the method is known, the method name is excluded from the actual lambda
expression. This concept is explored in the upcoming syntax and example sections.
An FI may have one or more default methods and one or more static methods.
Default methods allow for the addition of new code to the interface, ensuring
backward compatibility. This ensures that legacy code that implements the interface

2 of 15

13/10/2016 10:25

OCA Java SE 8 Programmer I Study Guide (Exa...

http://viewer.books24x7.com/AssetViewer.aspx?...

will not break if the new default methods are not used. (Note that default and static
methods in the context of FIs are not on the exam.) An example of an FI that also
includes default methods is Javas Predicate FI:

Larger View

Larger View

The Predicate FI is one of many general-purpose FIs, which are included in the
java.util.function package for the primary use of features of the JDK.
General-purpose FIs are listed in Table H-2 in Appendix H. The Predicate FI will
be visited later in the chapter, because you will see this FI on the exam.
The Java SE 8 API has several specific-purpose functional interfaces as well, and
the number will continue to grow as the API is extended and refined. Various
specific-purpose FIs are listed in Table H-1 of Appendix H.
Instances of functional interfaces can be created with method references,
constructor references, and lambda expressions.
FIs should be annotated with the @FunctionalInterface annotation to aid the
compiler in checking for specification adherence and the IDE in features support.
An example of IDE features support would be refactoring of anonymous inner
classes to lambda expressions.

Lambda Expressions
Lambda expressions allow for the creation and use of single method classes.
These methods have a basic syntax that provides for the omission of modifiers, the
return type, and optional parameters. Full syntax includes a parameter list with
explicit or implicit target types, the arrow operator, and the body with statements. A
target type is the type of object in which a lambda is bound. Multiple target types
must be enclosed in parentheses. A body with multiple statements must be
enclosed in braces. Therefore, syntax for lambda expressions is either of these:

Larger View

3 of 15

13/10/2016 10:25

OCA Java SE 8 Programmer I Study Guide (Exa...

http://viewer.books24x7.com/AssetViewer.aspx?...

Various examples of lambda expressions syntax are shown in Table 11-1.

Table 11-1: Lambda Expressions Syntax Examples

Lambda expressions can appear in any of these contexts: assignments, array


initializers, cast expressions, constructor arguments, lambda bodies, method
arguments, return statements, ternary expressions, and variable declarations.
The body of lambda expressions that return a value are considered to be valuecompatible, and those that do not are considered to be void-compatible.
On the Job

Pipelines and streams are not on the exam, although they


work hand-in-hand with lambda expressions. A pipeline is a
sequence of aggregate operations, connected through
method chaining. Streams are seen with classes that
support functional-style operations on streams of elements.
The following code demonstrates refactoring of the
enhanced-for loop toward use of the implicit Stream
interface and a lambda expression. A stream is a sequence
of elements that supports sequential and parallel aggregate
operations.

Larger View

Larger View

4 of 15

13/10/2016 10:25

OCA Java SE 8 Programmer I Study Guide (Exa...

http://viewer.books24x7.com/AssetViewer.aspx?...

Lambda Expressions and FI Example


In this section, well demonstrate the use of a lambda expression with a functional
interface. Well take a look at refactoring an anonymous inner class into a lambda
expression. For this example, well make use of the Comparator FI. To build up to
use of the Comparator FI, lets look at the Comparator interface in three
contexts:
q Comparator interface implemented from a class
q Comparator interface used with an anonymous inner class
q Comparator functional interface used with a lambda expression

Because objects often need to be compared, methods in the Collections class


assume that objects in the collection are comparablewhich is the case, for
example, when you are sorting an ArrayList. However, if there is no natural
ordering, the Comparator interface can be used to specify the desired ordering of
the objects.

Comparator Interface Implemented from a Class


If we wanted to compare water from various sources, wed have to implement a
helper class to specify which piece of state would be used for sortingin this case,
the state would be the source.
The helper class would be WaterSort, which implements the Comparator
interface.

Larger View

The Water class represents the value/transfer bean.

Larger View

5 of 15

13/10/2016 10:25

OCA Java SE 8 Programmer I Study Guide (Exa...

http://viewer.books24x7.com/AssetViewer.aspx?...

Lets look at a simple program that exercises the sort and use of the Water transfer
object. Here, we build an array list of Water objects and then perform an
alphabetical sort on them by instantiating the WaterSort class that implements
the Comparator interface.

Larger View

Larger View

6 of 15

13/10/2016 10:25

OCA Java SE 8 Programmer I Study Guide (Exa...

http://viewer.books24x7.com/AssetViewer.aspx?...

Comparator Interface Used with an Anonymous Inner Class


If you are going to use code only once and you will not reuse it, there is no practical
need to maintain it (for example, the WaterSort class) as a stand-alone piece of
code. As with this example, it would be most ideal to replace the WaterSort class
with an inline anonymous inner class. This means you can remove the
WaterSort class altogether and replace the code in the main method, from
WaterSort waterSort = new WaterSort();, to this:

Larger View

Comparator Functional Interface Used with a Lambda Expression


Comparator isnt just an interface; its an FI. Remember that FIs have one
abstract method originating within its interface. However, FIs can also include public
abstract method declarations from java.lang.Object. Again, FIs may
optionally have one or more default methods and one or more static methods, but
typically they have zero of each.
In the next code listing, the following items are present in Javas Comparator FI:
q The interface is annotated with @FunctionalInterface
q One and only one abstract method; int compare(T o1, T o2);
q Inclusion of the java.lang.Object abstract method declaration boolean
equals(Object obj);
q Overloaded default methods: thenComparing
q Static methods: naturalOrder(), overloaded comparing(), comparingInt(),
comparingLong(), comparingDouble()

None of these specific details of the Comparator FI will be on the exam, but it is
good to see how an FI can be constructed and that it follows the rules, as shown in
the next code listing. If any of the rules are broken in the coding of the interface,
compiler errors will be thrown, thanks to the inclusion of the
@FunctionalInterface annotation.

7 of 15

13/10/2016 10:25

OCA Java SE 8 Programmer I Study Guide (Exa...

http://viewer.books24x7.com/AssetViewer.aspx?...

Larger View

Larger View

Larger View

8 of 15

13/10/2016 10:25

OCA Java SE 8 Programmer I Study Guide (Exa...

http://viewer.books24x7.com/AssetViewer.aspx?...

Larger View

Java SE 8 aims to solve the vertical issue of several lines of code with a simpler
expressive means with lambda expressions. Thus, the six lines of code shown in
the anonymous inner class example can be replaced with the following abbreviated
code statement using the Comparator FI in the context of a lambda expression:

Larger View

To reduce SLOC (source lines of code) further, Collections.sort() can be


used to reduce the use of two lines of code (or statements) to one.

Larger View

Also, since the target types are known, the expression can be further simplified by
removing the class names, so (Water w1, Water w2) would be (w1, w2).

Larger View

9 of 15

13/10/2016 10:25

OCA Java SE 8 Programmer I Study Guide (Exa...

http://viewer.books24x7.com/AssetViewer.aspx?...

Simpler even (and you can probably use this on the job right away) is that the
Comparator class provides a comparingWith method that accepts a lambda
expression. The return value of this method can be used with the sort method of
various collection types (such as ArrayList):

Larger View

Predicate Functional Interface


As previously discussed, the Predicate FI is included on the exam. Its general
definition is quite simple, with a generic as the target type and the abstract method
being test. The test method returns a Boolean value.

Three classes are provided here that will collectively help demonstrate the use of
lambda expressions through five similar scenarios:
q PlanetApp Application that creates planet objects and queries filtered planet lists using the
Predicate FI
q Planet A value/transfer object representing planets as basic Java Beans
q PlanetPredicates A helper class making use of predicates

Lets list the Planet class first, because its just a simple bean showing a Planet
object with state representing their names, primary color, number of moons, and
whether or not the planets have rings.

Larger View

Larger View

10 of 15

13/10/2016 10:25

OCA Java SE 8 Programmer I Study Guide (Exa...

http://viewer.books24x7.com/AssetViewer.aspx?...

Next, the PlanetPredicates class listing is provided. This class demonstrates


different features, such as using predicates in the return statement of methods.
These features are examined in more detail against the associated scenarios.

Larger View

Now, lets look at the source code for the application. Well step through each
scenario that uses lambda expressions, one at a time. Note that the scenarios
provide standard output listings where the Predicate FI has been used to assist
with the task. The five scenarios are listed here from a general user goal
perspective, followed by the overall source code, and then a general description of
each scenario.
q
q
q
q
q

Scenario 1: Which planets have rings?


Scenario 2: Which planets are blue and have moons?
Scenario 3: Which planets have more than twenty moons?
Scenario 4: Which planet has a color (other than black)?
Scenario 5: Which planets have moons?

Larger View

11 of 15

13/10/2016 10:25

OCA Java SE 8 Programmer I Study Guide (Exa...

http://viewer.books24x7.com/AssetViewer.aspx?...

Larger View

Larger View

Scenario 1: Which Planets Have Rings?


In this scenario, a lambda expression is passed into a method call as an argument.
By using an enhanced for loop, you can see the Planet target type and the
test method that belong to the Predicate FI.

Larger View

12 of 15

13/10/2016 10:25

OCA Java SE 8 Programmer I Study Guide (Exa...

http://viewer.books24x7.com/AssetViewer.aspx?...

Here the method is called, accepting the Predicate type in the second argument:

Larger View

Notice that replacing the enhanced for loop with a pipeline is beneficial, and in
most cases, your IDE can do it for you.

Larger View

Scenario 2: Which Planets Are Blue and Have Moons?


Determining which planets are blue and have moons, we use streams, filters, and
the foreach method. None of these elements is on the exam, but you will surely
be using them on the jobthat is, if you decide to use functional programming in
your Java space.

Larger View

Scenario 3: Which Planets Have More Than Twenty Moons?


Passing lambda expressions can still be a little too implicit, so you may find it
beneficial to create helper classes that work with the expressions behind the
scenes, as in the supplied PlanetPredicates class example. In the main
method, a very simple method is called, providing two arguments to produce our
list.

Larger View

Here, the filterPlanets() and hasMoonsMoreThan() methods do the work


for us, while leveraging off of the use of the lambda expression:

13 of 15

13/10/2016 10:25

OCA Java SE 8 Programmer I Study Guide (Exa...

http://viewer.books24x7.com/AssetViewer.aspx?...

Larger View

Scenario 4: Which Planet Has a Color (Other Than Black)?


This scenario is very similar to scenario 3, except the method used to return lambda
expressions through a Predicate parameter is done so in a pipeline versus a
straight method call.

Larger View

Scenario 5: Which Planets Have Moons?


To determine which planets have moons, we will be modifying the ArrayList to
remove all elements that dont have moons. We can do this easily because the
ArrayList class provides a removeIf method that accepts a Predicate.

Larger View

In our scenario, the list is simply modified to remove elements where


numberOfMoons is equal to zero:

Larger View

As you should be deeply familiar with the syntax by now, youll know that the
lambda could have been abbreviated even further:

Larger View

EXERCISE 11-1: IDE Refactoring for Lambda Expressions


In this exercise, youll use an IDE to refactor an anonymous inner class to a lambda
expression.

1. Install the latest version of the NetBeans IDE.

14 of 15

13/10/2016 10:25

OCA Java SE 8 Programmer I Study Guide (Exa...

http://viewer.books24x7.com/AssetViewer.aspx?...

2. Create a new JavaFX project (choose File | New Project, select JavaFX,
select JavaFXApplication, click Next, and click Finish). A JavaFX application
will be created that includes an anonymous inner class.

3. In the Projects pane, expand the JavaFXApplication, Source Packages, and


javafxapplication nodes. Click the JavaFXApplication.java filename so the file
is opened in the source code editor. Scroll down to line 26, which begins with
btn.setOnAction.

4. Click the light bulb in the glyph gutter at line 26. Notice that if you hover the
mouse over the light bulb, you will see this message: This anonymous inner
class creation can be turned into a lambda expression.

5. Click Use Lambda Expression. The conversion will be automatic. Examine


the conversion to understand what you did.
Use of content on this site is subject to the restrictions set forth in the Terms of Use.
Page Layout and Design 2016 Skillsoft Ireland Limited - All rights reserved, individual content is owned by
respective copyright holder.

15 of 15

13/10/2016 10:25

S-ar putea să vă placă și