From the course: Functional Programming with Java

Unlock the full course today

Join today to access over 22,500 courses taught by industry experts or purchase this course individually.

Collect in Java

Collect in Java - Java Tutorial

From the course: Functional Programming with Java

Start my 1-month free trial

Collect in Java

- [Instructor] The final built-in list processing function that we're going to discuss in this course is called collect. So far, we've only been using this function to transform our streams back into lists, but it can actually do quite a bit more than that. Java's collect function is actually quite similar to reduce, except it's more flexible. Notice that because reduce requires us to pass a binary operator function, the return value of reduce is restricted to being the same type as the elements of the stream that it's operating on. And this means that for example, if we're reducing a list of strings, the return value of reduce has to be a string, or if we're reducing a list of integers, the return value of reduce has to be an integer. With collect, however, there are no such restrictions. So as we've seen the basic syntax of collect is like this. We call .collect on a stream and pass it something called a collector. Now, unlike the other special types that we've seen so far, such as…

Contents