Search code examples
javaspringspring-webfluxreactive-programmingproject-reactor

Losing return Type information When Mono flatmap collecting


I wrote code like below using Reactor

    private Mono<Map<String, A>> resolve(Mono<Map<String, List<B>>> bMapMono) {
        return bMapMono.flatMap(bMap -> bMap.entrySet().stream()
                                                     .map(entry -> toAfunc(entry.getKey(), entry.getValue()))
                                                     .filter(Objects::nonNull)
                                                     .collect(Collectors.<A, String, A>toMap(x -> x.getStringKey(), Function.identity())));
    }

But it display error in compiler intellij

like this

Required type: Mono <Map<String, A>> 
Provided: Mono <Object>

How can I solve this?


Solution

  • I was able to reproduce the error in IntelliJ. It seems as though the lambda in your Mono::flatMap is returning a Map, while what you want to return is a Mono. While you could solve the issue by wrapping the lambda result in a mono, you might want to consider using the reactor-methods which support what you might be trying to achieve with your stream. Consider the following:

            return bMapMono.flatMapIterable(Map::entrySet)
                    .mapNotNull(entry -> toAfunc(entry.getKey(), entry.getValue()))
                    .collect(Collectors.toMap(A::getStringKey, Function.identity()));