O'Reilly logo

Functional Programming in Java by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required