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());`