By default, all streams are ordered. That means that any ordered operations on both serial and parallel streams will have the same effect:
// note the use of a TreeSet - which imposes order by sorting
TreeSet<Integer> sequence = new TreeSet<>();
System.out.println("Building sequence");
for (int i=0; i < 1000000; i++) {
sequence.add(i);
}
System.out.println("Serial stream");
sequence.stream().skip(10000).findFirst().ifPresent(System.out::println);
// output 10000
System.out.println("Ordered Parallel stream");
sequence.stream().parallel().skip(10000).findFirst().ifPresent(System.out::println);
// still outputs 10000 - even though parallel used
System.out.println("Unordered Parallel stream");
sequence.stream().unordered().parallel().skip(10000).findFirst().ifPresent(System.out::println);
// doesnt always output 10000
inserting the unordered() intermediate operation can have performance benefits for downstream parallel operators since they no longer are constrained by order
By default, all streams are ordered. That means that any ordered operations on both serial and parallel streams will have the same effect:
inserting the
unordered()
intermediate operation can have performance benefits for downstream parallel operators since they no longer are constrained by order