如何将 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;
            })));

我可以用更少的代码实现这一点吗?


答案 1

如果您出于任何原因不必创建流,则可以从输入创建Flux,映射它并收集列表

Flux.fromIterable(inputs).flatMap(processor::process).collectList();

答案 2
// first merge all the `Mono`s:
List<Mono<Output>> outputs = ...
Flux<Output> merged = Flux.empty();
for (Mono<Output> out : outputs) {
    merged = merged.mergeWith(out);
}

// then collect them
return merged.collectList();

或(灵感来自亚历山大的答案)

Flux.fromIterable(outputs).flatMap(x -> x).collectList();

推荐