如何从给定的两个Flux中获取共同元素?

huangapple go评论76阅读模式
英文:

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&lt;String&gt;```


</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&lt;List&lt;String&gt;&gt; getCommonElements(Flux&lt;String&gt; flux1, Flux&lt;String&gt; flux2) {
    return flux1.collectList().zipWith(flux2.collectList())
            .map(tuple2 -&gt; {
                List&lt;String&gt; commonElements = new ArrayList&lt;&gt;(tuple2.getT2());
                commonElements.retainAll(tuple2.getT1());
                return commonElements;
            });
            // If you want to return a Mono&lt;Boolean&gt;
            // .map(List::isEmpty);
}

This returns a Mono&lt;List&lt;String&gt;&gt; on top of which you can build your further logic on.

huangapple
  • 本文由 发表于 2020年8月28日 16:34:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63630259.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定