java - 如何在Mono<Map<Entity, Integer>>上调用entrySet方法

标签 java functional-programming reactive-programming spring-webflux

假设我有一个方法findAll,它返回 Flux<Song>来自ReactiveMongoRepository<Song, String> .

下面我使用传统的 java 流方法来查找 @Naman 建议的 x 得票最多的歌曲:

return songRepository.findAll()
    .collect(Collectors.toMap(Function.identity(), this::getSumOfVotes))
    .entrySet().stream() --entrySet method is not recognized by IntelliJ
    .sorted(Map.Entry.<Song,Integer>comparingByValue().reversed())
    .limit(numberOfTopSongs)
    .collect(Collectors.toMap(e -> e.getKey().getId(), Map.Entry::getValue, (a, b) -> a, LinkedHashMap::new));

以上解决方案适用于 Iterable , SetList但是当我假装调用方法 entrySet 时就会出现问题上Mono<Map<Song, Integer>> 。这是我第一次深入了解 Web Flux这就是为什么我有点困惑为什么方法 entrySet不适用于 Mono类型。

我发现了一段代码,例如:

Mono<Map<ByteBuffer, ByteBuffer>> serializedMap = Flux.fromIterable(() -> map.entrySet().iterator())
        .collectMap(entry -> rawKey(entry.getKey()), entry -> rawValue(entry.getValue()));

但我尽量避免重新包装我的:

songRepository.findAll()
        .collect(Collectors.toMap(Function.identity(), this::getSumOfVotes))

Flux.fromIterable再次。

如果您对我做错的事情提出建议或如何跳过此障碍,我将不胜感激。

最佳答案

这是 Map<Song, Integer>其中有entrySet方法;如果您想对 Mono 的内容应用一些转换,使用 map :

Mono<Map<Song, Integer>> songs = ...;
Mono<Set<Map.Entry<Song, Integer>> = songs.map(Map::entrySet);

请注意map是这种方法的常见名称,可以在 Flux 上找到。 , Stream

关于java - 如何在Mono<Map<Entity, Integer>>上调用entrySet方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60412780/

相关文章:

java - AnnotationConfigApplicationContext@4c0bc4 尚未刷新

java - 为什么当我输入 itemName 后我的程序无法继续运行?

Java Lambda 引用封闭对象 : Replace with Private Static Class?

java - Webflux如何从流内部设置cookie

javascript - 用 observable 替换回调 hell

java - 如何创建嵌入式 WebSocket 服务器 Jetty 9?

java - 序列化 Guava 的 ImmutableTable

Scala 表达式求值

curry 时的 Groovy 错误

java - Spring Webflux TEXT_EVENT_STREAM_VALUE 不流式传输