所以我有这个程序来计算具有相同键但不同值的所有宠物店的总和。但是,现在,我想计算具有相同 key 的每个宠物店的平均值。我正在考虑使用计数器来获取宠物店在数组列表中包含的次数。但这不起作用。我需要为每个循环运行另一个循环吗?
public class AverageCost {
public void calc(ArrayList<Pet> pets) {
Map<String, Double> hm = new HashMap<>();
for (Pet i : pets) {
String name = i.getShop();
// If the map already has the pet use the current value, otherwise 0.
double price = hm.containsKey(name) ? hm.get(name) : 0;
price += i.getPrice();
hm.put(name, price);
}
System.out.println("");
for (String key : hm.keySet()) {
System.out.printf("%s: %s%n", key, hm.get(key));
}
}
最佳答案
您要求的是一种计算累积移动平均值的算法,而不存储您迄今为止积累的术语数量。我认为这是不可能的(例如,请参阅https://en.wikipedia.org/wiki/Moving_average#Cumulative_moving_average,其中需要“n”,即到目前为止的项数)。我的建议是使用两次传递 - 第一个用于存储数字,第二个用于计算平均值。
public void calc(List<Pet> pets) {
// First pass
Map<String, List<Double>> firstPass = new HashMap<>();
for (Pet pet : pets) {
String name = pet.getShop();
if (firstPass.containsKey(name)) {
firstPass.get(name).add(pet.getPrice());
} else {
List<Double> prices = new ArrayList<>();
prices.add(pet.getPrice());
firstPass.put(name, prices);
}
}
// Second pass
Map<String, Double> results = new HashMap<>();
for (Map.Entry<String, List<Double>> entry : firstPass.entrySet()) {
Double average = calcAverage(entry.getValue());
results.put(entry.getKey(), average);
// Print results
System.out.printf("%s: %s%n", entry.getKey(), average);
}
}
private double calcAverage(List<Double> values) {
double result = 0;
for (Double value : values) {
result += value;
}
return result / values.size();
}
关于java - 如何计算具有相同键的 HashMap 值的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36556264/