问题描述
假设我有一个带有 findAll()
方法的存储库,该方法返回 State
的 Iterable
,其中 State
是一个代表美国州的类,它有两个字段(带有 getter/setter):name
和 population
.
Suppose I have a repository with a findAll()
method that returns an Iterable
of State
, where State
is a class representing a US state that has two fields (with getter/setters): name
, and population
.
我想获得 Flux 中所有 State
的人口字段的总和.我从一个 Iterable 创建了一个 Flux,如下所示:
I want to get the sum of the population fields for all State
s in my Flux. I create a Flux from an Iterable, as follows:
Flux f = Flux.fromIterable(stateRepo.findAll());
我有 Flux,但我不知道总结其值的好方法.我试过类似
I've got my Flux, but I don't know of a good way to sum up its values. I've tried something like
int total = 0;
f.map(s -> s.getPopulation()).subscribe(p -> total += v);
return total;
但是,编译器说总数应该是最终的或有效的最终".添加 final
显然不起作用,因为我正在尝试添加它.
However, the compiler says that total "should be final or effectively final". Adding final
obviously won't work, because I'm trying to add to it.
如何对 Flux 求和(或任何其他聚合函数)?
How do I go about summing (or any other aggregate function) on a 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
}
这篇关于如何对 Reactor Flux 流中的值求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!