Java Reference
In-Depth Information
Example 5-4. The ordering assumption in this test will always work
List
<
Integer
>
numbers
=
asList
(
1
,
2
,
3
,
4
);
List
<
Integer
>
stillOrdered
=
numbers
.
stream
()
.
map
(
x
->
x
+
1
)
.
collect
(
toList
());
// Reliable encounter ordering
assertEquals
(
asList
(
2
,
3
,
4
,
5
),
stillOrdered
);
Set
<
Integer
>
unordered
=
new
new
HashSet
<>(
numbers
);
List
<
Integer
>
stillUnordered
=
unordered
.
stream
()
.
map
(
x
->
x
+
1
)
.
collect
(
toList
());
// Can't assume encounter ordering
assertThat
(
stillUnordered
,
hasItem
(
2
));
assertThat
(
stillUnordered
,
hasItem
(
3
));
assertThat
(
stillUnordered
,
hasItem
(
4
));
assertThat
(
stillUnordered
,
hasItem
(
5
));
Some operations are more expensive on ordered streams. This problem can be solved by
eliminating ordering. To do so, call the stream's
unordered
method. Most operations,
however, such as
filter
,
map
, and
reduce
, can operate very efficiently on ordered streams.
This can cause unexpected behavior, for example,
forEach
provides no guarantees as to en-
counter order if you're using parallel streams. (This will be discussed in more detail in
your friend!
Enter the Collector
Earlier, we used the
collect(toList())
idiom in order to produce lists out of streams. Ob-
viously, a
List
is a very natural value to want to produce from a
Stream
, but it's not the only
value that you might want to compute. Perhaps you want to generate a
Map
or a
Set
. Maybe
you think it's worth having a domain class that abstracts the concept you want?
You've already learned that you can tell just from the signature of a
Stream
method whether
it's an eagerly evaluated terminal operation that can be used to produce a value. A
reduce