Parallel Streams And Encounter Order
parallelStream splits work across the common pool: forEach drops encounter order, forEachOrdered restores it, while sum and findFirst stay deterministic.
Code
import java.util.List;
public class ParallelOrder {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// 串行流:forEach 按相遇顺序(encounter order)逐个处理
System.out.print("sequential: ");
numbers.stream().forEach(n -> System.out.print(n + " "));
System.out.println();
// parallelStream 把流拆给公共池多个线程:forEach 不保证相遇顺序
System.out.print("parallel: ");
numbers.parallelStream().forEach(n -> System.out.print(n + " "));
System.out.println();
// forEachOrdered 强制按相遇顺序处理,代价是牺牲部分并行度
System.out.print("ordered: ");
numbers.parallelStream().forEachOrdered(n -> System.out.print(n + " "));
System.out.println();
// 归约与查找不受拆分影响:sum 满足结合律,findFirst 仍按相遇顺序
int sum = numbers.parallelStream().mapToInt(Integer::intValue).sum();
int first = numbers.parallelStream().findFirst().orElseThrow();
System.out.println("sum = " + sum + ", first = " + first);
}
}How it works
Parallel Streams And Encounter Order comes down to the class ParallelOrder and the function main.
Stream stages compose left to right — nothing executes until the terminal operation runs.
Putting it to use
Running the file prints labeled results such as sequential:, parallel:, ordered: — each operation’s effect is visible in the output.
Core lines
int sum = numbers.parallelStream().mapToInt(Integer::intValue).sum();
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
int first = numbers.parallelStream().findFirst().orElseThrow();
Interactive Tools for This Topic
FAQ
- What does Parallel Streams And Encounter Order print when run?
- Execute the whole file; each printed line is prefixed with a label like `sequential:`, `parallel:`, `ordered:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.