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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36554356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 01:35:15  来源:igfitidea点击:

how to sum hashmap values with same key java

javahashmap

提问by Daniel O Mensah

So I am having a problem where I have to add up all values with the same key in my HashMap. The data(petshop and pet price) is retrieve from an 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
and another Law Pet shop: 5.00,
I would like to output it like this:
Law Pet shop: 13.00.
Here is the code and output:

所以我遇到了一个问题,我必须将 HashMap 中具有相同键的所有值相加。数据(宠物店和宠物价格)是从 ArrayList 中检索的。目前,程序只获取每个商店的最后一个值,因为有多个商店名称相同但宠物价格不同。我希望能够总结每家商店的宠物价格。因此,如果我们有例如
Law Pet shop: 7.00
和另一个 Law Pet shop: 5.00,
我想这样输出:
Law Pet shop: 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());
        }
    }
}

At the moment this is the output:

目前这是输出:

Aquatic Acrobatics: 7.06
The Briar Patch Pet Store: 5.24
Preston Pets: 18.11
The Menagerie: 18.7
Galley Pets: 16.8
Anything Except Badgers: 8.53
Petsmart: 21.87
Morris Pets and Supplies: 7.12

水上杂技:7.06
The Briar Patch Pet Store:5.24
Preston Pets:18.11
The Menagerie:18.7
厨房宠物:16.8
除了獾之外的任何东西:8.53
Petsmart:21.87
Morris 宠物和用品:7.12

回答by Elliott Frisch

First, please program to the interface (not the concrete collection type). Second, please don't use raw types. Next, your Maponly needs to contain the name of the pet and the sum of the prices (so String, Double). Something like,

首先,请编程到接口(不是具体的集合类型)。其次,请不要使用原始类型。接下来,您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));
    }
}

回答by krasinski

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

回答by Alex Kolokolov

There is a useful method V getOrDefault(Object key, V defaultValue)in the Mapinterface. It returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key. In our case it could be used like this:

有一个有用的方法V getOrDefault(Object key, V defaultValue)Map界面。它返回指定键映射到的值,如果此映射不包含键的映射,则返回 defaultValue。在我们的例子中,它可以这样使用:

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

回答by Raghu K Nair

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

;

;