당신은지도의 가중 평균을 계산하기 위해이 절차를 사용할 수 있습니다. 지도 항목의 키에는 값이 포함되어야하며지도 항목의 값에는 가중치가 포함되어야합니다.
/**
* 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;
}
단위 테스트를 통해 사용 사례를 볼 수 있습니다.
import org.junit.Assert;
import org.junit.Test;
당신은 코드에 대한 이러한 수입이 필요합니다 :
import java.util.HashMap;
import java.util.Map;
나는 그것이 도움이되기를 바랍니다
/**
* 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));
}
당신은 단위 테스트에 대한 이러한 수입이 필요합니다.
[Collectors.averagingDouble'] (https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#averagingDouble-java.util.function)을 확인 했습니까? .ToDoubleFunction-) 메서드? – Aaron