Search code examples
javadictionaryspring-webfluxfluxcollect

How to collect Flux of Map into Mono of Map (Flux<Map<String,String>> into Mono<Map<String,String>>)?


I have found an extensive thread of how to merge maps in java8 streams, but I cannot quite translate that to Webflux.

I have two Fluxes of the form:

Flux<Map<String, List<String>>> fluxOne = Flux.fromIterable(
    List.of(
        Collections.singletonMap("one", List.of("one","two")),
        Collections.singletonMap("two", List.of("one","two"))));
Flux<Map<String, String>> fluxTwo = Flux.fromIterable(
    List.of(
        Collections.singletonMap("one", "two"),
        Collections.singletonMap("one", "two")));

I'd like to transform that into Mono's by collecting it's values:

Mono<Map<String, List<String>>> monoOne = fluxOne.collect(...);
Mono<Map<String, String>> monoTwo = fluxTwo.collect(...);

So my question, how do I do that?


Solution

  • Perhaps this is what you are looking for:

    Mono<Map<String, List<String>>> monoOne = fluxOne.collect(HashMap::new, Map::putAll);
    Mono<Map<String, String>> monoTwo = fluxTwo.collect(HashMap::new, Map::putAll);