17 Lambdas and Streams
Objectives
In this chapter you’ll:
Learn various functional-
programming techniques and
Create streams representing
ranges of int values and
random int values.
Implement functional
interfaces with lambdas.
mapToDouble and sorted,
and terminal operations
collect, forEach,
findFirst and reduce.
Process infinite streams.
Self-Review Exercises 2
Self-Review Exercises
17.1 Fill in the blanks in each of the following statements:
a) Lambda expressions implement .
b) With iteration the library determines how to access all the elements in a col-
lection to perform a task.
c) Functional programs are easier to (i.e., perform multiple operations simulta-
neously) so that your programs can take advantage of multi-core architectures to en-
hance performance.
d) An implementation of the functional interface takes two T arguments, per-
e) An implementation of the functional interface takes a T argument and returns
a boolean, and tests whether the T argument satisfies a condition.
f) A(n) represents an anonymous method—a shorthand notation for imple-
menting a functional interface.
g) Intermediate stream operations are —they aren’t performed until a terminal
operation is invoked.
h) The terminal stream operation performs processing on every element in a
stream.
i) lambdas use local variables from the enclosing lexical scope.
j) A performance feature of lazy evaluation is the ability to perform evaluation—
that is, to stop processing the stream pipeline as soon as the desired result is available.
k) For Maps, a BiConsumer’s first parameter represents the and its second rep
17.2 State whether each of the following is true or false. If false, explain why.
a) Lambda expressions can be used anywhere functional interfaces are expected.
b) Terminal operations are lazy—they perform the requested operation when they are
called.
c) Method reduce’s first argument is formally called an identity value—a value that, when
combined with a stream element using the IntBinaryOperator, produces the stream el
ement’s original value. For example, when summing the elements, the identity value is
1, and when getting the product of the elements, the identity value is 0.
d) Stream method findFirst is a short-circuiting terminal operation that processes the
stream pipeline but terminates processing as soon as an object is found.
3Chapter 17 Lambdas and Streams
e) Stream method flatMap receives a Function that maps a stream into an object. For ex-
ample, the object could be a String containing words and the result could be another
intermediate Stream<String> for the individual words.
f) When a class implements an interface with default methods and overrides them, the
class inherits the default methods’ implementations. An interface’s designer can now
evolve an interface by adding new default and static methods without breaking ex-
isting code that implements the interface.
17.3 Write a lambda or method reference for each of the following tasks:
a) Write a lambda that can that can be passed to a method with an IntConsumer parameter.
The lambda should display its argument followed by a space.
b) Write a method reference that can be used in place of the following lambda:
(String s) -> {return s.toUpperCase();}
c) Write a no-argument lambda that implicitly returns the String “Welcome to lambdas!”.
d) Write a method reference for Math method sqrt.
e) Create a one-parameter lambda that returns the cube of its argument.
Exercises
NOTE: Solutions to the programming exercises are located in the ch12solutions folder.
Each exercise has its own folder named ex17_## where ## is a two-digit number representing
the exercise number. For example, Exercise 17.10’s solution is located in the folder ex17_10.
17.4 Fill in the blanks in each of the following statements:
a) Stream are formed from stream sources, intermediate operations and termi-
nal operations.
b) The following code uses the technique of iteration:
c) Functional programming capabilities focus on —not modifying the data
source being processed or any other program state.
d) An implementation of the functional interface takes a T argument and returns
void, and performs a task with its T argument, such as outputting the object, invoking
a method of the object, etc.
1int sum = 0;
2
3for (int counter = 0; counter < values.length; counter++) {
4 sum += values[counter];
5}
© 2018 Pearson Education, Inc., 330 Hudson Street, NY NY 10013. All rights reserved.
Exercises 4
e) An implementation of the functional interface takes no arguments and pro
duces a value of type Tthis is often used to create a collection object in which a stream
operations results are placed.
f) Streams are objects that implement interface Stream and enable you to perform func-
tional programming tasks on of elements.
g) The intermediate stream operation results in a stream containing only the el-
ements that satisfy a condition.
h) place the results of processing a stream pipeline into a collection such as a
List, Set or Map.
i) Calls to filter and other intermediate streams are lazy—they aren’t evaluated until an
eager operation is performed.
j) Pattern method uses a regular expression to tokenize a String and create a
k) Functional interfaces must contain only one method, but may also contain
and static methods that are fully implemented in the interface declarations.
17.5 State whether each of the following is true or false. If false, explain why.
a) An intermediate operation specifies tasks to perform on the stream’s elements; this is
efficient because it avoids creating a new stream.
b) Reduction operations take all values in the stream and turn them into a new stream.
c) If you need an ordered sequence of int values, you can create an IntStream containing
such values with IntStream methods range and rangeClosed. Both methods take two
int arguments representing the range of values. Method rangeClosed produces a se-
quence of values from its first argument up to, but not including, its second argument.
Method range produces a sequence of values including both of its arguments.
d) Class Files (package java.nio.file) is one of many classes throughout the Java APIs
that have been enhanced to support Streams.
e) Interface Map does not contain any methods that return Streams.
f) The Function interface has methods apply (abstract), compose (abstract), andThen
(default) and identity (static).
5Chapter 17 Lambdas and Streams
g) If one class inherits the same default method from two interfaces, the class must over-
ride that method; otherwise, the compiler does not know which method to use, so it
generates a compilation error.
Exercises 6
17.6 Write a lambda or method reference for each of the following tasks:
a) Write a lambda expression that receives two double parameters a and b and returns their
product. Use the lambda form that explicitly lists the type of each parameter.
b) Rewrite the lambda expression in Part (c) using the lambda form that does not list the
type of each parameter.
c) Rewrite the lambda expression in Part (d) using the lambda form that implicitly returns
the value of the lambda’s body expression.
d) Write a no-argument lambda that implicitly returns the string “Welcome to lambdas!”.
e) Write a constructor reference for class ArrayList.
f) Reimplement the following statement using a lambda as the event handler:
17.7 What’s wrong with the following stream pipeline?
17.8 Assuming that list is a List<Integer>, explain in detail the stream pipeline:
1slider.valueProperty().addListener(
2 new ChangeListener<Number>() {
3 @Override
4 public void changed(ObservableValue<? extends Number> ov,
5 Number oldValue, Number newValue) {
6 System.out.printf(“The slider’s new value is %s%n”, newValue);
7 }
8 }
9);
1list.stream()
2 .filter(value -> value % 2 != 0)
3 .sum()
1list.stream()
2 .filter(value -> value % 2 != 0)
3 .reduce(0, Integer::sum)
© 2018 Pearson Education, Inc., 330 Hudson Street, NY NY 10013. All rights reserved.
17.9 Assuming that random is a SecureRandom object, explain in detail the stream pipeline:
1random.ints(1000000, 1, 3)
2 .boxed()
3 .collect(Collectors.groupingBy(Function.identity(),
4 Collectors.counting()))
5 .forEach((side, frequency) ->
6 System.out.printf(“%-6d%d%n”, side, frequency));
© 2018 Pearson Education, Inc., 330 Hudson Street, NY NY 10013. All rights reserved.