Java Reference
In-Depth Information
collect(toList())
NOTE
collect(toList())
is an eager operation that generates a list from the values in a
Stream
.
The values in the
Stream
that are operated on are derived from the initial values and the re-
cipe produced by the sequence of
Stream
calls. In fact,
collect
is a very general and power-
ample of this operation:
List
<
String
>
collected
=
Stream
.
of
(
"a"
,
"b"
,
"c"
)
.
collect
(
Collectors
.
toList
());
assertEquals
(
Arrays
.
asList
(
"a"
,
"b"
,
"c"
),
collected
);
This example shows how
collect(toList())
can be used to build a result list out of a
Stream
. It's important to remember, as discussed in the previous section, that because many
Stream
functions are lazy, you do need to use an eager operation such as
collect
at the end
of a sequence of chained method calls.
This example also shows the general format for all the examples in this section. It starts by
. Finally, we perform an assert to show you what the results are equal to .
You can think of the opening call to
stream
and the closing call to a
collect
or other ter-
minal method as
bun
methods. They aren't the actual filling of our stream burger, but they do
help us see where the operations begin and end.