Parallel Streams

As mentioned above streams can be either sequential or parallel. Operations on sequential streams are performed on a single thread while operations on parallel streams are performed concurrently on multiple threads.

The following example demonstrates how easy it is to increase the performance by using parallel streams.

First we create a large list of unique elements:

  1. int max = 1000000;
  2. List<String> values = new ArrayList<>(max);
  3. for (int i = 0; i < max; i++) {
  4. UUID uuid = UUID.randomUUID();
  5. values.add(uuid.toString());
  6. }

Now we measure the time it takes to sort a stream of this collection.

Sequential Sort

  1. long t0 = System.nanoTime();
  2. long count = values.stream().sorted().count();
  3. System.out.println(count);
  4. long t1 = System.nanoTime();
  5. long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
  6. System.out.println(String.format("sequential sort took: %d ms", millis));
  7. // sequential sort took: 899 ms

Parallel Sort

  1. long t0 = System.nanoTime();
  2. long count = values.parallelStream().sorted().count();
  3. System.out.println(count);
  4. long t1 = System.nanoTime();
  5. long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
  6. System.out.println(String.format("parallel sort took: %d ms", millis));
  7. // parallel sort took: 472 ms

As you can see both code snippets are almost identical but the parallel sort is roughly 50% faster. All you have to do is change stream() to parallelStream().