问题
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