Search code examples
javajava-streamsequential

IntStream, when should I really use sequential() method


When I do this:

IntStream i = IntStream.of(5,6,7,1,2,3,4);
//IntStream o =  i.sequential();
i.forEach(System.out::println);

I get the same response whether I call sequential or not.Then what are the use cases of sequential() method.

Assuming I am processing millions of ints on multicore machine, unless I call sequential(), is it possible jvm will try to do the processing in parallel?


Solution

  • For example when you have a parallel stream:

    IntStream i = IntStream.of(5, 6, 7, 1, 2, 3, 4);
    i.parallel();
    i = i.sequential();
    i.forEach(System.out::println);
    

    Wil always return 5, 6, 7, 1, 2, 3, 4 But when you remove i.sequential(), you can get other results because it runs in parallel.