Java Reference
In-Depth Information
.filter(d -> d.getCalories() > 300)
.limit(3)
.collect(toList());
Figure 5.3 illustrates a combination of filter and limit. You can see that only the first three
elements that match the predicate are selected and the result is immediately returned.
Figure 5.3. Truncating a stream
Note that limit also works on unordered streams (for example, if the source is a Set). In this case
you shouldn't assume any order on the result produced by limit.
5.1.4. Skipping elements
Streams support the skip(n) method to return a stream that discards the first n elements. If the
stream has fewer elements than n, then an empty stream is returned. Note that limit(n) and
skip(n) are complementary! For example, the following code skips the first two dishes that have
more than 300 calories and returns the rest. Figure 5.4 illustrates this query:
 
Search WWH ::




Custom Search