0

I was curious whether parallel() can be used with sorted(), so I wrote a quick test:

List<Integer> testArray = ImmutableList.of(3, 4, 2, 1, 5, 7, 2, 3, 4, 54, 1, 5, 1, 3, 2, 5, 1, 3, 4, 5, 6, 3, 6, 2, 15,6,6,3 ,3,4,5,2,44);
        List<Integer> testResult = testArray.stream().parallel()
                .sorted(Comparator.naturalOrder())
                .collect(Collectors.toList());
        System.out.println(testResult);

Result: [1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7, 15, 44, 54]

However, I'm still not quite sure, even after reading the documentation: https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

So, is it safe to use?

Jon Tan
  • 1,461
  • 3
  • 17
  • 33
  • 2
    Yes. It is safe to use. **But**, it's probably slower than not using `parallel()`. There is overhead to starting and coordinating multiple threads, and sorting a trivial `List` can almost certainly be done faster by a single thread. – Elliott Frisch Jun 13 '19 at 00:21
  • Also beware of : https://stackoverflow.com/questions/19529982/java-8-parallelstream-with-sorted – racraman Jun 13 '19 at 01:30

0 Answers0