This intermediate operation returns an equivalent stream that is sequential. May return itself, either because the stream was already sequential, or because the underlying stream state was modified to be sequential.
package com.logicbig.example.stream;
import java.time.LocalTime;
import java.util.concurrent.TimeUnit;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
public class SequentialExample {
public static void main(String... args) {
UnaryOperator<Integer> iterator = integer -> integer + 1;
System.out.println("-- sequential ---");
Stream.iterate(1, iterator)
.limit(5)
.sequential()
.forEach(SequentialExample::process);
System.out.println("-- parallel ---");
Stream.iterate(1, iterator)
.parallel()
.limit(5)
.forEach(SequentialExample::process);
}
private static void process(Integer integer) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(integer + " - " + LocalTime.now());
}
}
Output
-- sequential ---
1 - 15:40:58.340
2 - 15:40:59.349
3 - 15:41:00.360
4 - 15:41:01.370
5 - 15:41:02.377
-- parallel ---
1 - 15:41:03.385
3 - 15:41:03.385
2 - 15:41:03.385
5 - 15:41:03.385
4 - 15:41:03.385