dvas0004 / NerdNotes

A collection of notes: things I'd like to remember while reading technical articles, technical questions I couldn't answer, and so on.
12 stars 0 forks source link

Java Ordered vs Unordered streams #81

Open dvas0004 opened 5 years ago

dvas0004 commented 5 years ago

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