Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why sorted operation impose an encounter order to a Stream?

The documentation of the sorted operation says :

For ordered streams, the sort is stable. For unordered streams, no stability guarantees are made.

and the page-summary says :

Some intermediate operations, such as sorted(), may impose an encounter order

Can someone explain why sorted operation needs an encounter order to the Stream (I don't see the relationship between the presence of an encounter order and the sorting operation) ?

Does that mean the following code is not valid (as HashSet is not intrinsically ordered) ?

Set<Integer> mySet = new HashSet<>();
mySet.add(10);
mySet.add(4);
mySet.add(20);
mySet.add(15);
mySet.add(22);
mySet.add(-3);

List<Integer> result = mySet.stream().sorted().collect(Collectors.toList());

System.out.println(result);

When I run this code, it always give me the same output [-3, 4, 10, 15, 20, 22]

Event if I use .parrallel(), the output remains the same [-3, 4, 10, 15, 20, 22]

mySet.stream().parallel().sorted().collect(Collectors.toList());`
like image 518
Olivier Boissé Avatar asked Dec 03 '19 19:12

Olivier Boissé


1 Answers

When I run this code, it always give me the same output

Yes. It sorts the set, as expected. It seems you have misinterpreted the word 'stable'. Stability in a sort refers to not moving equal elements.

Stable sort algorithms sort repeated elements in the same order that they appear in the input

Read more on Wikipedia

Your list has no repeated elements, so stability does not apply, and you cannot determine stability by observing the output.

Can someone explain why sorted operation needs an encounter order to the Stream

It doesn't. The quote says it may "impose an encounter order". That is, there will be a defined encounter order after the sort operation, not that there is required to be one before.

like image 161
Michael Avatar answered Sep 19 '22 08:09

Michael