Java Reference
In-Depth Information
filtering beef
mapping beef
filtering chicken
mapping chicken
[pork, beef, chicken]
You can notice several optimizations due to the lazy nature of streams. First, despite the fact
that many dishes have more than 300 calories, only the first three are selected! This is because
of the limit operation and a technique called
short-circuiting
, as we'll explain in the next chapter.
Second, despite the fact that filter and map are two separate operations, they were merged into
the same pass (we call this technique
loop fusion
).
4.4.2. Terminal operations
Terminal operations produce a result from a stream pipeline. A result is any nonstream value
such as a List, an Integer, or even void. For example, in the following pipeline, forEach is a
terminal operation that returns void and applies a lambda to each dish in the source. Passing
System.out.println to forEach asks it to print every Dish in the stream created from menu:
menu.stream().forEach(System.out::println);
Quiz 4.1: Intermediate vs. terminal operations
In the stream pipeline that follows, can you identify the intermediate and terminal operations?
long count = menu.stream()
.filter(d -> d.getCalories() > 300)
.distinct()
.limit(3)
.count();
Answer:
The last operation in the stream pipeline count returns a long, which is a non-Stream value. It's
therefore a
terminal operation
. All previous operations, filter, distinct, limit, are connected and
return a Stream. They are therefore
intermediate operations
.
Search WWH ::
Custom Search