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());`
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With