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 h
You can use this procedure to calculate the weighted average of a map. Note that the key of the map entry should contain the value and the value of the map entry should contain the weight.
/**
* Calculates the weighted average of a map.
*
* @throws ArithmeticException If divide by zero happens
* @param map A map of values and weights
* @return The weighted average of the map
*/
static Double calculateWeightedAverage(Map map) throws ArithmeticException {
double num = 0;
double denom = 0;
for (Map.Entry entry : map.entrySet()) {
num += entry.getKey() * entry.getValue();
denom += entry.getValue();
}
return num / denom;
}
You can look at its unit test to see a usecase.
/**
* Tests our method to calculate the weighted average.
*/
@Test
public void testAveragingWeighted() {
Map map = new HashMap<>();
map.put(0.7, 100);
map.put(0.5, 200);
Double weightedAverage = calculateWeightedAverage(map);
Assert.assertTrue(weightedAverage.equals(0.5666666666666667));
}
You need these imports for the unit tests:
import org.junit.Assert;
import org.junit.Test;
You need these imports for the code:
import java.util.HashMap;
import java.util.Map;
I hope it helps.