Java Stream How to - Sum in parallel








Question

We would like to know how to sum in parallel.

Answer

import java.util.stream.Stream;

public class Main {
  public static void main(String...args){
    long l = Stream.iterate(1L, i -> i + 1).limit(300).parallel().reduce(Long::sum).get();
    System.out.println(l);
  }
}

The code above generates the following result.