所以我遇到了一个问题,我必须在HashMap中使用相同的键添加所有值.数据(petshop和宠物价格)是从ArrayList中检索的.目前,该计划只获得每个商店的最后价值,因为有多个商店名称相同但宠物价格不同.我想能够为每个商店的宠物价格加起来.所以,如果我们有例如,
法律宠物店:7.00
和另一个法律宠物店:5.00,
我想这样输出:
法律宠物店:13.00.
这是代码和输出:
public class AverageCost {
public void calc(ArrayList<Pet> pets){
String name = "";
double price = 0;
HashMap hm = new HashMap();
for (Pet i : pets) {
name = i.getShop();
price = i.getPrice();
hm.put(name, price);
}
System.out.println("");
// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
}
}
Run Code Online (Sandbox Code Playgroud)
目前这是输出:
水上杂技:7.06
Briar Patch宠物店:5.24
普雷斯顿宠物:18.11
动物园:18.7
厨房宠物:16.8
除獾之外的任何东西:8.53
Petsmart:21.87
Morris宠物及用品:7.12
首先,请编程到界面(而不是具体的集合类型).其次,请不要使用原始类型.接下来,您Map只需要包含宠物的名称和价格的总和(如此String, Double).就像是,
public void calc(List<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: %.2f%n", key, hm.get(key));
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
在 Java 8 中,您可以使用 Streams api 来执行此操作:
Map<String, Double> map =
pets.stream().collect(
Collectors.groupingBy(
Pet::getShop,
Collectors.summingDouble(Pet::getPrice)
)
);
Run Code Online (Sandbox Code Playgroud)