Chapter SEVENTEEN
Peeking, Mapping, Reducing and Collecting


Exam Objectives

Develop code to extract data from an object using peek() and map() methods including primitive versions of the map() method.
Save results to a collection using the collect method and group/partition data using the Collectors class.
Use of merge() and flatMap() methods of the Stream API.

Answers

1. The correct answer is B.
partitioningBy() always returns a map with two keys, even if one key contains an empty list. Since the predicate returns true for all the elements of the stream, they are placed on the list of the true key.


2. The correct answer is D.
Option A is not equivalent because partitioningBy() returns a map with a Boolean as a key.
Option B doesn't compile, partitioningBy() takes a predicate as an argument (a lambda expression that must return a boolean).
Option C is not equivalent because it will create a map with keys of type Boolean.
Option D is equivalent because by default, groupingBy() creates a map whose values are of type List<T>.


3. The correct answer is D.
The program prints something like this:
[Ljava.lang.String;@87aac27
The mapping function converts each element of the stream to an array of strings.

Then, limit(1) returns the first element of the stream, an array containing ["a", "a", "a", "a", "a"], which is passed to System.out.print().


4. The correct answer is A.
For each element of the stream, flatMap() returns a stream with the element three times repeated. The streams are merged into one and this is converted to a List, which is printed.


5. The correct answer is B.
Option A doesn't compile. reduce() takes a BinaryOperator, not a Predicate.
Option B is the right way to implement OptionalInt min() with a reduce operation.
Option C is incorrect because it doesn't return an Optional.
Option D doesn't compile. minBy() takes a Comparator.


6. The correct answer is D.
Option A is incorrect, it must return an Optional.
Option B is incorrect, it must return just T.
Option C is incorrect, it's missing the first argument, U identity.


7. The correct answer is C.
The type of the resulting map is:

TreeMap<Integer, Map<Boolean, List<Integer>>>

Elements are collected in a TreeMap, which has a natural order by default so we can discard Option A.

Keys of the map will be the remainder after dividing by 10 each element: 6, 4, 1, 1, 8, 8, 6. Values with the same key are appended to a List so we can discard Option B because it is missing a 98.

A downstream collector, partitioningBy(), partitions each value of the map into two groups, depending on whether the individual elements are greater than 5 or not, so Option B is also discarded.