Java Stream How to - Is Stream Parallel








Question

We would like to know how to is Stream Parallel.

Answer

/* w w  w.  jav a 2  s  .  com*/
import java.util.Arrays;
import java.util.List;

public class Main {
  public static void main(String[] args) {


    List<Integer> l = Arrays.asList(4,3,5,7,2,2,3,5);

    l.stream()
            .reduce((a, b) -> a + b).ifPresent(System.out::println);

    l.parallelStream()
            .reduce((a, b) -> a + b).ifPresent(System.out::println);

    System.out.println("isParallel list.stream(): "
            + l.stream().isParallel());

    System.out.println("isParallel list.stream().parallel(): "
            + l.stream().parallel().isParallel());

    System.out.println("isParallel list.parallelStream(): "
            + l.parallelStream().isParallel());

    System.out.println("isParallel list.parallelStream().sequential(): "
            + l.parallelStream().sequential().isParallel());
  }

}

The code above generates the following result.