February 2014
Intermediate to advanced
160 pages
4h 59m
English
We’ve used the collect method a few times in the examples to gather Stream elements into an ArrayList. This method is a reduce operation that’s useful for transforming the collection into another form, often a mutable collection. The collect function, when combined with the utility methods of the Collectors class, provides a wealth of conveniences, as we’ll see in this section.
Let’s examine the power of collect using the Person list as an example. Suppose we want to collect only people older than 20 years from the original list. Here’s a version that uses mutability and forEach.
| compare/fpij/OlderThan20.java | |
| | List<Person> olderThan20 = new ArrayList<>(); |
| | people.stream() |
| | .filter(person ... |