How to calculate the average of a Project Reactor Flux?

早过忘川 提交于 2020-11-30 00:11:45

问题


I have a method that returns a Flux<SensorData>, let's suppose SensorData has a field measure: Integer.

I would like to calculate the average value of measure of the whole Flux. How can it be done?


val sensorFlux: Flux<SensorData> = sensorRepository.findAll()
...


回答1:


Mono<Double> average = sensorFlux.collect(Collectors.averagingInt(SensorData::getMeasure))



回答2:


Another way of doing it with an auxiliary object:

val average = sensorFlux.map { it.measure }
                .map { Measure(1, it) }
                .reduce { t: Measure, u: Measure -> Measure(t.elements + u.elements, t.sum + u.sum) }
                .map { it.sum / it.elements }

---

data class Measure(var elements: Int, var sum: Long)


来源:https://stackoverflow.com/questions/57008214/how-to-calculate-the-average-of-a-project-reactor-flux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!