简体   繁体   English

如何从另一个 Flux 中排除 Flux 中的所有元素

[英]How to exclude all elements in Flux from another Flux

I have two Flux s one for successful elements another one holding the erroneous elements我有两个Flux一个用于成功元素,另一个用于保存错误元素

Flux<String> success= Flux.just("Orange", "Apple", "Banana","Grape", "Strawberry");
Flux<String> erroneous = Flux.just("Banana","Grape",);

How can i filter the first Flux to execlude all the elements from the second one?如何过滤第一个Flux以排除第二个 Flux 中的所有元素?

You may wish to consider collecting the Flux into a set, caching that set, and then using filterWhen as follows:您可能希望考虑将Flux收集到一个集合中,缓存该集合,然后使用filterWhen如下:

Mono<Set<String>> erroneousSet = erroneous.collect(Collectors.toSet()).cache();
Flux<String> filtered = success.filterWhen(v -> erroneousSet.map(s -> !s.contains(v)));

Gives:给出:

Orange
Apple
Strawberry

This isn't the most concise solution (see below), but it enables the contents of erroneous to be cached.这不是最简洁的解决方案(见下文),但它可以缓存erroneous的内容。 In this specific example that's a moot point, but if it's a real-world situation (not using Flux.just() ) then erroneous could be recomputed on every subscription, and that could end up being incredibly (and unnecessarily) expensive in performance terms.在这个具体的例子中,这是一个有争议的问题,但如果它是真实世界的情况(不使用Flux.just() ),那么每次订阅都可能重新计算erroneous ,并且最终可能会在性能方面变得难以置信(并且不必要地)昂贵.

Alternatively, if the above really doesn't matter in your use case, filterWhen() and hasElement() can be used much more concisely as follows:或者,如果上述内容在您的用例中确实无关紧要,则可以更简洁地使用filterWhen()和 hasElement( hasElement() ,如下所示:

success.filterWhen(s -> erroneous.hasElement(s).map(x->!x))

Or with reactor-extra:或者使用 reactor-extra:

success.filterWhen(s -> BooleanUtils.not(erroneous.hasElement(s)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM