How to add elements to a hashmap in Java?

Use the put() method to add elements to a HashMap in Java.

In this post, we’ll learn more than just how to add elements to a HashMap in Java.

How to add another String value to the existing HashMap Key without overwriting?

What are you hoping to achieve here?

Map (the HashMap) in your case is a direct “mapping” from one “key” to another value.

E.g.

"foo" -> 123
"bar" -> 321
"far" -> 12345
"boo" -> 54321

This means that if you were to try:

myHashMap.get("foo");

It would return the value 123 (of course, the type of the value you return can be anything you want).

Of course, this also means that any changes you make to the value of the key, it overrides the original value you assigned it, just like changing the value of a variable will override the original one assigned.

Say:

myHashMap.put("foo", 42);

The old value of "foo" in the map would be replaced with 42. So it would become:

"foo" -> 42
"bar" -> 321
"far" -> 12345
"boo" -> 54321

However, if you need multiple String objects that are mapped from a single key, you could use a different object which can store multiple objects, such as an Array or a List (or even another HashMap if you wanted.

For example, if you were to be using ArrayLists, when you are assigning a value to the HashMap, (say it is called myHashMap), you would first check if the key has been used before, if it hasn’t, then you create a new ArrayList with the value you want to add, if it has, then you just add the value to the list.

(Assume key and value have the values you want)

ArrayList<String> list;
if(myHashMap.containsKey(key)){
    // if the key has already been used,
    // we'll just grab the array list and add the value to it
    list = myHashMap.get(key);
    list.add(value);
} else {
    // if the key hasn't been used yet,
    // we'll create a new ArrayList<String> object, add the value
    // and put it in the array list with the new key
    list = new ArrayList<String>();
    list.add(value);
    myHashMap.put(key, list);
}

You can do like this!

Map<String,List<String>> map = new HashMap<>();
.
.
if(map.containsKey(key)){
    map.get(key).add(value);
} else {
   List<String> list = new ArrayList<>();
   list.add(value);
   map.put(key, list);
}

Or you can do the same thing by one line code in Java 8 style .

map.computeIfAbsent(key, k ->new ArrayList<>()).add(value);

How to update a value, given a key in a hashmap?

map.put(key, map.get(key) + 1);

should be fine. It will update the value for the existing mapping. Note that this uses auto-boxing. With the help of map.get(key) we get the value of the corresponding key, then you can update with your requirement. Here I am updating to increment value by 1.

Java 8 way:

You can use computeIfPresent method and supply it a mapping function, which will be called to compute a new value based on existing one.

For example,

Map<String, Integer> words = new HashMap<>();
words.put("hello", 3);
words.put("world", 4);
words.computeIfPresent("hello", (k, v) -> v + 1);
System.out.println(words.get("hello"));

Alternatively, you could use merge method, where 1 is the default value and function increments existing value by 1:

words.merge("hello", 1, Integer::sum);

In addition, there is a bunch of other useful methods, such as putIfAbsentgetOrDefaultforEach, etc.

How to update the value in Hashmap using a hashmap?

We use the put() method with HashMap when we want to insert a value into the HashMap . And we can also use it to update the value inside the HashMap. 

How to get keys from value in HashMap?

To find all the keys that map to a certain value, we can loop the entrySet() and Objects. equals to compare the value and get the key. The common mistake is use the entry. getValue()

Sample query related to HashMaps:

I am new to HashMaps. I was wondering if I could add ask the user what he or she wanted the key to be and what they wanted the value to be. So far I am getting the HashMap to print out but for some reason when I ask for the view the value it returns null and when I try to remove the key it also doesn’t remove it.

import java.util.Scanner;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapDemo {
  public static void main (String [] args){
    //declaring a hashmap   
    HashMap<Integer, String> hm = new HashMap<Integer, String>();

    //adding elements to the hashmap
    hm.put(1, "Josh");
    hm.put(2, "Max");
    hm.put(3, "Karan");

    //declaring the Scanner
    Scanner sc = new Scanner(System.in);
    System.out.println("Would you like to add Elements to the hashmap?");
    String scYN = sc.nextLine();
    scYN = scYN.toLowerCase();
    if(scYN.equals("yes")) {
        System.out.println("What would the key to be?");
        int key = sc.nextInt();
        sc.nextLine();
        System.out.println("What would the value to be?");
        String val = sc.nextLine();
        hm.put(key, val);           
    }else if (scYN.equals("no")) {
        System.out.println("False");
    }else{
        System.out.println("False");
    }

    //displaying content 
    Set set = hm.entrySet();
    Iterator iterator = set.iterator();
    while(iterator.hasNext()){
        Map.Entry mentry = (Map.Entry)iterator.next();
        System.out.print("Key is: "+ mentry.getKey() + " & Value is: ");
        System.out.println(mentry.getValue());
    }

    /* Get values based on key*/

    System.out.println("What value would you like to find?");
    String fVal = sc.nextLine();        
    String var= hm.get(fVal);
    System.out.println("Value at index " + fVal + " is: "+ var);

    /* Remove values based on key*/

    System.out.println("Would you like to remove a key?");
    String remKey = sc.nextLine();
    hm.remove(remKey);
    System.out.println("Map key and values after removal:");
    Set set2 = hm.entrySet();
    Iterator iterator2 = set2.iterator();
    while(iterator2.hasNext()) {
        Map.Entry mentry2 = (Map.Entry)iterator2.next();
        System.out.print("Key is: "+mentry2.getKey() + " & Value is: ");
        System.out.println(mentry2.getValue());
    }

}

Answer:

It gives you a null value because when you use get(), the key being passed as a paramanter (fVal) is a String, whereas in the Hashmap has its key defined as an Integer.

To solve this issue, have the fVal variable be an Integer that gets the nextInt()

int fVal = sc.nextInt();

You did this when soliciting data-entry, “What would the key to be?”. Do the same when prompting for search criterion, “What value would you like to find?”, and when prompting for deletion, “Would you like to remove a key?”.

Hope you learned something from this post.

Follow Programming Articles for more!

About ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ

Linux and Python enthusiast, in love with open source since 2014, Writer at programming-articles.com, India.

View all posts by ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ →