how to sum hashmap values with same key java

16,705

Solution 1

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

Solution 2

In Java 8 you could use streams api to do this:

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

Solution 3

There is a useful method V getOrDefault(Object key, V defaultValue) in the Map interface. 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:

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:

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

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

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

Solution 4

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

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

;

Share:
16,705
Daniel O Mensah
Author by

Daniel O Mensah

About me I’ve been always fascinated in how computers work and particularly, how software work. Information Technology has become essential in our lives and in the business area because it allows us to accomplish tasks and deal with issues that occur in our lifetime. Solving problems, understanding various computer concepts and use algorithm for calculation is what amazed me. My goal is to expand my knowledge which will enable me to start-up my own business and to contribute to the development of future technologies. In order to accomplish my ambition, I would like to study at a higher level and obtain a Software Engineering degree. I studied Information Technology level 3 at Croydon College and I have developed a passion for Event Driven Programming. I was voted as class representative in level one and level three. The role of class representative helped me to improve my listening, leadership and public speaking skills. In addition, I developed the ability to understand other people issues, be tolerant and loyal to people. I eloquently speak Italian and one Ghanaian dialect at a good standard. Projects In my second year, I worked as coordinator in a team for a project which required my group and I to create a Learning Management System called LearnInSpace. My role was to coordinate the team and also work on the back-end using PHP and MYSQLi to store and display information from the database. Another important role was to help my team mates with any difficulties therefore I also worked on the front end by developing the website template with HTML5, CSS3 and Bootstrap. My responsibilities also required me to set meetings and time-box tasks using MS Project. At the end of every meeting, I record the attendance and outcome of the meeting. Through the time I managed to learn android programming and develop an android app called Croydon TramTime. Since where I live in Croydon there’s no app to check the tram time, I developed an android app that provides trams arrivals and departures. Croydon citizens are now able to check the trams time by downloading the app in the Google play store. I developed my first application called Tap the Kiwi when I was in college. I used visual basic to create a game where players click on the kiwi button in order to gain points. Each click is valued as 1 point. However, there are also 5 levels where players need to get through in order to finish the game. To accomplish each level, players need to gain a certain amount of points in a specific amount of time or otherwise they will loose and start from the beginning. If a player does not reach a certain amount of points, the game will not allow him/her to proceed with the game and force the user to start from the beginning.

Updated on June 14, 2022

Comments

  • Daniel O Mensah
    Daniel O Mensah about 2 years

    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:

    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