gpt4 book ai didi

java - 如何对 Reactor Flux 流中的值求和?

转载 作者:搜寻专家 更新时间:2023-10-31 08:25:13 25 4
gpt4 key购买 nike

假设我有一个带有 findAll() 方法的存储库,该方法返回 StateIterable,其中 State 是一个表示美国州的类,它有两个字段(带有 getter/setter):namepopulation

我想获取我的 Flux 中所有 State 的人口字段总和。 我从 Iterable 创建了一个 Flux,如下所示:

Flux f = Flux.fromIterable(stateRepo.findAll());

我有 Flux,但我不知道总结其值的好方法。 我试过类似的东西

int total = 0;
f.map(s -> s.getPopulation()).subscribe(p -> total += v);
return total;

但是,编译器表示总计“应该是最终的或实际上是最终的”。添加 final 显然行不通,因为我正在尝试添加它。

如何对 Flux 求和(或任何其他聚合函数)?

最佳答案

使用reduce方法:

@GetMapping("/populations")
public Mono<Integer> getPopulation() {
return Flux.fromIterable(stateRepo.findAll())
.map(s -> s.getPopulation())
.reduce(0, (x1, x2) -> x1 + x2)
.map(this::someFunction); // here you can handle the sum
}

关于java - 如何对 Reactor Flux 流中的值求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49018111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com