Using the collect Method and the Collectors Class
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 ... |
Get Functional Programming in Java now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.