如何将 List<Mono<T>> 转换为 Mono<List<T>>?
2022-09-03 09:20:28
我有一个返回的方法:Mono<Output>
interface Processor {
Mono<Output> process(Input input);
}
我想为集合执行此方法:processor
List<Input> inputs = // get inputs
Processor processor = // get processor
List<Mono<Output>> outputs = inputs.stream().map(supplier::supply).collect(toList());
但是,我想要得到的不是包含聚合结果的。List<Mono<Output>>
Mono<List<Output>>
我试过了,但最终结果看起来很笨拙:reduce
Mono<List<Output>> result = inputs.stream().map(processor::process)
.reduce(Mono.just(new ArrayList<>()),
(monoListOfOutput, monoOfOutput) ->
monoListOfOutput.flatMap(list -> monoOfOutput.map(output -> {
list.add(output);
return list;
})),
(left, right) ->
left.flatMap(leftList -> right.map(rightList -> {
leftList.addAll(rightList);
return leftList;
})));
我可以用更少的代码实现这一点吗?