在使用流计算笛卡尔积时,我可以并行生成它们,并按顺序使用它们,以下代码演示了这一点:
int min = 0;
int max = 9;
Supplier<IntStream> supplier = () -> IntStream.rangeClosed(min, max).parallel();
supplier.get()
.flatMap(a -> supplier.get().map(b -> a * b))
.forEachOrdered(System.out::println);
这将按顺序完美打印所有内容,现在考虑以下代码,我想将其添加到列表中,同时保留顺序。
int min = 0;
int max = 9;
Supplier<IntStream> supplier = () -> IntStream.rangeClosed(min, max).parallel();
List<Integer> list = supplier.get()
.flatMap(a -> supplier.get().map(b -> a * b))
.boxed()
.collect(Collectors.toList());
list.forEach(System.out::println);
现在它没有按顺序打印!
这是可以理解的,因为我在任何地方都没有要求保留订单。
现在的问题是:有没有一种方法可以collect()
保持Collector
秩序?