I’m quite new in the reactive world
My code looks like this:
Flux.fromIterable(list) .collectMap(a -> a.getName(), b-> functionReturningMonoOfC(b) .map(C::url) .block();
The result is of type Map<String, Mono<String>>
. I would like it to be of type Map<String, String>
. Any ideas?
Advertisement
Answer
I suggest to use flatMap
operator before collecting the elements into a Map
public class ReactorApp { record Person(String name){} public static Mono<String> functionReturningMono(Person person) { return Mono.just("Hello " + person.name()); } public static void main(String[] args) { List<Person> persons = List.of( new Person("John"), new Person("Mike"), new Person("Stacey") ); Map<String, String> result = Flux.fromIterable(persons) .flatMap(person -> functionReturningMono(person) .map(String::toUpperCase) .map(message -> Map.entry(person.name(), message))) .collectMap(Map.Entry::getKey, Map.Entry::getValue) .block(); System.out.println("Result : " + result); // Result : {Mike=HELLO MIKE, Stacey=HELLO STACEY, John=HELLO JOHN} } }