英文:
How to get a common element from 2 given Flux?
问题
Sure, here's the translation:
给定两个 Flux-
```java
Flux<String> flux1 = ...
Flux<String> flux2 = ...
现在我需要检查是否有一个共同的字符串出现在这两个 Flux 中。检查之后,响应可能是布尔值或者一个 List<String>
。
<details>
<summary>英文:</summary>
Given 2 Flux-
Flux<String> flux1 = ...
Flux<String> flux2 = ...
Now I need to check if a common String is present in both the Flux. After checking, response could either be boolean or a ```List<String>```
</details>
# 答案1
**得分**: 0
Flux是一个持续的元素流,它会发射0至N个元素,然后完成(成功或出现错误)。因此在这种情况下,我们将不得不将这些值聚合到一个列表中,以便在它们变得可用时。您可以使用Flux的`collectList()`操作符。
```java
public Mono<List<String>> getCommonElements(Flux<String> flux1, Flux<String> flux2) {
return flux1.collectList().zipWith(flux2.collectList())
.map(tuple2 -> {
List<String> commonElements = new ArrayList<>(tuple2.getT2());
commonElements.retainAll(tuple2.getT1());
return commonElements;
});
// 如果您想返回一个Mono<Boolean>
// .map(List::isEmpty);
}
这会返回一个Mono<List<String>>
,您可以在其上构建进一步的逻辑。
英文:
Flux is a continuous stream of elements that emits 0 to N elements, and then completes (successfully or with an error). So in this case we will have to aggregate the values into a List as they become available. You can make use of collectList()
operator of Flux.
public Mono<List<String>> getCommonElements(Flux<String> flux1, Flux<String> flux2) {
return flux1.collectList().zipWith(flux2.collectList())
.map(tuple2 -> {
List<String> commonElements = new ArrayList<>(tuple2.getT2());
commonElements.retainAll(tuple2.getT1());
return commonElements;
});
// If you want to return a Mono<Boolean>
// .map(List::isEmpty);
}
This returns a Mono<List<String>>
on top of which you can build your further logic on.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论