Bạn có thể sử dụng phương pháp này để tính bình quân gia quyền của bản đồ. Lưu ý rằng khóa của mục nhập bản đồ phải chứa giá trị và giá trị của mục nhập bản đồ phải chứa trọng số.
/**
* 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<Double, Integer> map) throws ArithmeticException {
double num = 0;
double denom = 0;
for (Map.Entry<Double, Integer> entry : map.entrySet()) {
num += entry.getKey() * entry.getValue();
denom += entry.getValue();
}
return num/denom;
}
Bạn có thể xem thử nghiệm đơn vị của nó để xem lượt sử dụng.
/**
* Tests our method to calculate the weighted average.
*/
@Test
public void testAveragingWeighted() {
Map<Double, Integer> map = new HashMap<>();
map.put(0.7, 100);
map.put(0.5, 200);
Double weightedAverage = calculateWeightedAverage(map);
Assert.assertTrue(weightedAverage.equals(0.5666666666666667));
}
Bạn cần những hàng nhập khẩu đối với các bài kiểm tra đơn vị:
import org.junit.Assert;
import org.junit.Test;
Bạn cần những hàng nhập khẩu đối với các mã:
import java.util.HashMap;
import java.util.Map;
Tôi hy vọng nó giúp.
Bạn đã kiểm tra ['Collectors.averagingDouble'] (https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#averagingDouble-java.util.function .ToDoubleFunction-) phương pháp? – Aaron