How do I go about calculating weighted mean of a Map where the Integer value is the weight for the Double value to be averaged.
eg: Map has following elements:
(0.7, 100) // value is 0.7 and weight is 100
(0.5, 200)
(0.3, 300)
(0.0, 400)
I am looking to apply the following formula using Java 8 streams, but unsure how to calculate the numerator and denominator together and preserve it at the same time. How to use reduction here?
解决方案
You can create your own collector for this task:
static Collector averagingWeighted(ToDoubleFunction valueFunction, ToIntFunction weightFunction) {
class Box {
double num = 0;
long denom = 0;
}
return Collector.of(
Box::new,