【问题标题】:Reactor filter out Flux<String> from List<String>Reactor 从 List<String> 中过滤掉 Flux<String>
【发布时间】:2021-08-23 17:58:03
【问题描述】:
假设我们有
-
List<String> list 包含 "A", "B", "C", "D"
-
Flux<String> flux 包含 "A", "B"
有没有办法从列表中过滤掉通量?换句话说,从列表中减去通量,结果应该是"C", "D"。
查看reactor的文档,filterWhen似乎是最接近的,但它只重播第一个匹配条件的元素,所有后续匹配都将被忽略。
这可以在非反应性世界中轻松实现,对于列表或集合,例如Subtracting one arrayList from another arrayList.
【问题讨论】:
标签:
java
spring-webflux
project-reactor
【解决方案1】:
您可能希望使用collectList() 方法。
Flux::collectList 将采用 Flux<String> 并发出 Mono<List<String>>。
这将使您能够方便地运行在该数据集上运行所需的任何集合比较操作。
这样,您可以提供一个.map() 操作,用于操作并将其转换为您想要的结果。
Mono<List<String>> monoWithRemovedElements = flux.collectList()
.map(fluxTurnedIntoList -> /*(subtract array list)*/)
如果您想将它扇回到 Flux 中,您可以使用 Mono::flatMapMany 方法。
Flux<String> fluxWithRemovedElements = monoWithRemovedElements
.flatMapMany(list -> Flux.fromIterable(list))
【解决方案2】:
您需要先将 Flux 转换为 ArrayList,然后根据 Flux 中的元素从列表中删除元素。
List<String> fluxedList = flux.collectList().block();
fluxedList.stream().forEach( elem -> list.remove(elem));