-4

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?

Naman
  • 27,789
  • 26
  • 218
  • 353

2 Answers2

3

As stated in the javadoc of IntStream.of, that method returns a sequential stream. So the sequential method will not have any effect.

Learn more about sequential and parallel streams in the official documentation: https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html.

mkczyk
  • 2,460
  • 2
  • 25
  • 40
cghislai
  • 1,751
  • 15
  • 29
  • I would like to see a coding example to see how it will be used whether it is called in parallel or not. – Vijayakumar Chava Feb 11 '20 at 21:02
  • 4
    @VijayakumarChava The function is just used to make the stream processing happen sequentially instead of in parallel. It's simply the inverse of calling `.parallel()`. Calling `sequential` on an already sequential stream will have no effect. – marstran Feb 11 '20 at 21:13
3

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.

Willem
  • 992
  • 6
  • 13
  • It makes sense now. When I run in parallel, sequence it is getting changed and so I need to call sequential() if I still need to read in the same order. It means calling sequential() has no impact but for in parallel processing. I still feel documentation is not very clear about it or I may have to understand more. Downgrading does not serve any purpose and one must read the question fully and understand its intent. – Vijayakumar Chava Feb 11 '20 at 22:08