Chapter THIRTEEN
Iterating and Filtering Collections


Exam Objectives

Collections Streams and Filters.
Iterate using forEach methods of Streams and List.
Filter a collection by using lambda expressions.

Answers

1. The correct answer is D.
Stream.of(T t) creates a stream of a single element, in this case of type List<Integer>. So i in the lambda expression has this type. Therefore, i - 1 is an invalid expression that generates a compiler error. To create a stream from this list, you have to use l.stream().


2. The correct answer is C.
Option A is false. filter is an intermediate operation.
Option B is false. filter is a stateless operation since the predicate of the filter is applied to each element of the stream independently.
Option C is true. Stream.forEach takes an implementation of the Consumer functional interface as an argument.
Option D is false. forEach is a terminal operation, so you can't chain two forEach operations.


3. The correct answer is B.
The filter operation generates a stream with only even values (2, 4, 6). A second filter generates a stream with values greater than three (4, 6), that are finally printed.


4. The correct answer is C.
The filter returns an empty stream (since none of the elements match the condition), so nothing else is filtered or printed.