Webflux collectMap 生成的 Mono<Map<String, Mono<String>>>
Webflux collectMap resulting Mono<Map<String, Mono<String>>>
我在反应世界中还很陌生
我的代码如下所示:
Flux.fromIterable(list)
.collectMap(a -> a.getName(),
b-> functionReturningMonoOfC(b)
.map(C::url)
.block();
结果的类型为 Map<String, Mono<String>>
。我希望它是 Map<String, String>
类型。有什么想法吗?
我建议在将元素收集到 Map
之前使用 flatMap
运算符
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}
}
}
我在反应世界中还很陌生
我的代码如下所示:
Flux.fromIterable(list)
.collectMap(a -> a.getName(),
b-> functionReturningMonoOfC(b)
.map(C::url)
.block();
结果的类型为 Map<String, Mono<String>>
。我希望它是 Map<String, String>
类型。有什么想法吗?
我建议在将元素收集到 Map
flatMap
运算符
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}
}
}