Skip to Content
Functional Programming in Java
book

Functional Programming in Java

by Venkat Subramaniam
February 2014
Intermediate to advanced
160 pages
4h 59m
English
Pragmatic Bookshelf
Content preview from Functional Programming in Java

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Functional Programming in Java

Functional Programming in Java

Pierre-Yves Saumont

Publisher Resources

ISBN: 9781941222690Errata Page