假设我有一个存储库findAll()
返回一个方法Iterable
of State
, where State
是一个代表美国州的类,有两个字段(带有 getter/setter):name
, and population
.
我想获得所有人口字段的总和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 进行求和(或任何其他聚合函数)?
Use reduce method:
@GetMapping("/populations")
public Mono<Integer> getPopulation() {
return Flux.fromIterable(stateRepo.findAll())
.map(s -> s.getPopulation())
.reduce(0, (x1, x2) -> x1 + x2)
.map(this::someFunction); //you can also handle the sum, if you wish
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)