Java Reference
In-Depth Information
When you create a
Stream
from a collection with a defined order, the
Stream
has a defined
encounter order. As a consequence,
Example 5-1
will always pass.
Example 5-1. The ordering assumption in this test will always work
List
<
Integer
>
numbers
=
asList
(
1
,
2
,
3
,
4
);
List
<
Integer
>
sameOrder
=
numbers
.
stream
()
.
collect
(
toList
());
assertEquals
(
numbers
,
sameOrder
);
If there's no defined order to begin, the
Stream
produced by that source doesn't have a
defined order. A
HashSet
is an example of a collection without a defined ordering, and be-
cause of that
Example 5-2
isn't guaranteed to pass.
Example 5-2. The ordering assumption here isn't guaranteed
Set
<
Integer
>
numbers
=
new
new
HashSet
<>(
asList
(
4
,
3
,
2
,
1
));
List
<
Integer
>
sameOrder
=
numbers
.
stream
()
.
collect
(
toList
());
// This may not pass
assertEquals
(
asList
(
4
,
3
,
2
,
1
),
sameOrder
);
The purpose of streams isn't just to convert from one collection to another; it's to be able to
provide a common set of operations over data. These operations may create an encounter or-
der where there wasn't one to begin with. Consider the code presented in
Example 5-3
.
Example 5-3. Creating an encounter order
Set
<
Integer
>
numbers
=
new
new
HashSet
<>(
asList
(
4
,
3
,
2
,
1
));
List
<
Integer
>
sameOrder
=
numbers
.
stream
()
.
sorted
()
.
collect
(
toList
());
assertEquals
(
asList
(
1
,
2
,
3
,
4
),
sameOrder
);
The encounter order is propagated across intermediate operations if it exists; for example, if
we try to
map
values and there's a defined encounter order, then that encounter order will be
preserved. If there's no encounter order on the input
Stream
, there's no encounter order on
weaker
hasItem
assertions on the
HashSet
example because the lack of a defined encounter
order from
HashSet
continues through the
map
.