假设我有一个findAll()
方法的存储库,它返回Iterable
的State
,其中State
是一个代表美国州的类,有两个字段(有getter / setter):name
和population
。
我想在我的Flux中得到所有State
s的总体字段。我从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
}
您可以从maven导入reactor额外包
io.projectreactor.addons:reactor-extra
然后使用MathFlux.sumInt(integresFlux)
docs:https://projectreactor.io/docs/core/release/reference/#extra-math