简体   繁体   English

如何用相同的键java求和hashmap值

[英]how to sum hashmap values with same key java

So I am having a problem where I have to add up all values with the same key in my HashMap.所以我遇到了一个问题,我必须将 HashMap 中具有相同键的所有值相加。 The data(petshop and pet price) is retrieve from an ArrayList.数据(宠物店和宠物价格)是从 ArrayList 中检索的。 at the moment, the program only gets the last value for each shop since there are multiple shops with the same name but different pet price.目前,程序只获取每个商店的最后一个值,因为有多个商店名称相同但宠物价格不同。 I would like to be able to sum the pet price for each shop.我希望能够总结每家商店的宠物价格。 so if we have for example,所以如果我们有例如
Law Pet shop: 7.00法律宠物店:7.00
and another Law Pet shop: 5.00,和另一家法律宠物店:5.00,
I would like to output it like this:我想像这样输出它:
Law Pet shop: 13.00.法律宠物店:13.00。
Here is the code and output:这是代码和输出:

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());
        }
    }
}

At the moment this is the output:目前这是输出:

Aquatic Acrobatics: 7.06水上杂技:7.06
The Briar Patch Pet Store: 5.24 Briar Patch 宠物店:5.24
Preston Pets: 18.11普雷斯顿宠物:18.11
The Menagerie: 18.7动物园:18.7
Galley Pets: 16.8厨房宠物:16.8
Anything Except Badgers: 8.53除了獾之外的任何东西:8.53
Petsmart: 21.87宠物智能:21.87
Morris Pets and Supplies: 7.12莫里斯宠物和用品:7.12

First, please program to the interface (not the concrete collection type).首先,请编程到接口(不是具体的集合类型)。 Second, please don't use raw types .其次,请不要使用原始类型 Next, your Map only needs to contain the name of the pet and the sum of the prices (so String, Double ).接下来,你的Map只需要包含宠物的名字和价格的总和(所以String, Double )。 Something like,类似的东西,

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));
    }
}

In Java 8 you could use streams api to do this:在 Java 8 中,您可以使用流 api 来执行此操作:

Map<String, Double> map = 
        pets.stream().collect(
            Collectors.groupingBy(
                Pet::getShop,
                Collectors.summingDouble(Pet::getPrice)
            )
        );

There is a useful method V getOrDefault(Object key, V defaultValue) in the Map interface. Map接口中有一个很有用的方法V getOrDefault(Object key, V defaultValue) It returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.它返回指定键映射到的值,如果此映射不包含键的映射,则返回 defaultValue。 In our case it could be used like this:在我们的例子中,它可以这样使用:

HashMap<String,Double> hm = new HashMap<>();

        for (Pet i : pets) {
            name = i.getShop();
            price = i.getPrice();

            hm.put(name, getOrDefault(name, 0) + price);
        }

In addition, we could get more elegant solution using method reference in Java 8:此外,我们可以使用 Java 8 中的方法引用获得更优雅的解决方案:

HashMap<String,Double> hm = new HashMap<>();

        for (Pet i : pets) {
            name = i.getShop();
            price = i.getPrice();

            hm.merge(name, price, Double::sum);
        }

If you the sum then you need add up the value you should be getting the value from HashMap and adding the price to that如果你是总和,那么你需要把你应该从 HashMap 获取的值加起来,然后加上价格

double price = hm.get(name) == null ? 0 : hm.get(name) ;
hm.put(name,price + i.getPrice())

; ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM