Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding values under same key HashMap in Java

I’m new to HashMaps, and I was wondering if there was a way to add values together if they have the same key.

For example, when I have the key ‘a’ and the value is 20 and later on I use the key ‘a’ again and the value is 10 the value should now be 30.

I don’t know how I would check if the Value already is in the HashMap and then use the same value again. The adding part could be done with just a variable that copies the current value and adds the new one, I guess.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you guys in advance.

>Solution :

I am guessing you want a hashmap for character vs integer and want to add the integer to already present value in case the value is present.You can do something like below:

public hashMapImpl(char ch, int number){
    Map<Character,Integer> map = new HashMap<>();
    if(map.containsKey(ch)){
        map.put(ch, map.get(ch)+number);
    }
    else{
        map.put(ch,number);
    }
}

Where ch will be your key and number will be something that you want to store at particular key.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading