【问题标题】:Spring Reactor Set of Sets Combine to a SetSpring Reactor Set 组合成一个 Set
【发布时间】:2019-10-31 11:51:29
【问题描述】:

我正在尝试弄清楚如何从 Flux<Order> 获取 Mono<Set<Customer>>

鉴于该订单包含Set<Customer>

我一直在尝试通读,这是我能得到的最接近的,但它仍然无法编译。有人可以帮忙吗?在以下示例中,orderService.getAll(orderCriteria) 返回Flux<Order>

final Mono<Set<Customer>> customerSetMono = orderService
              .getAll(orderCriteria)
              .map(order -> order.getCustomers())
              .collect(Collectors.toSet()) //Mono<Set<Set<Customer>>
              .flatMap(
                  customerSet -> customerSet.stream()
                      .flatMap(customers -> customers.stream()))
              .collect(Collectors.toSet());

【问题讨论】:

  • orderService.getAll(orderCriteria) 返回什么流?看起来应该是.flatMap(order -&gt; order.getCustomers().stream())
  • 所以 getAll() 返回订单通量
  • final Mono> customerSetMono = orderService .getAll(orderCriteria) .flatMap(order -> order.getCustomers().stream()) .collect(Collectors.toSet());也没有编译
  • orderService.getAll(orderCriteria).map(order -&gt; order.getCustomers()).flatMapIterable(customers -&gt; customers).collect(Collectors.toSet())
  • 更短的形式 - orderService.getAll(orderCriteria).flatMapIterable(Order::getCustomers).collect(Collectors.toSet())

标签: java-8 java-stream reactive-programming spring-webflux project-reactor


【解决方案1】:

您在list 场景中面临list,但处于反应式上下文中。因此,您需要做的就是使用flatMap 的适当变体。你的代码应该是这样的

orderService.getAll(orderCriteria) // Flux<Order>
        .flatMapIterable(Order::getCustomers) // Flux<Customer>
        .collect(Collectors.toSet()); // Mono<Set<Customer>>

【讨论】:

  • 谢谢你能详细说明为什么我们不能使用流方式
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-19
  • 1970-01-01
  • 2022-11-20
  • 2020-07-04
  • 2018-02-14
  • 1970-01-01
相关资源
最近更新 更多