jxc
jxc

Reputation: 163

Java - Adding another String value to existing HashMap Key without overwriting?

I was wondering if someone would be able to help with regards to adding another String value to an existing key within a HashMap in Java?

I understand that you can add a Key-Value pair using the this.put("String", "String") method. However, it overwrites the existing value, whereas I would like multiple values stored and paired, with the same key?

Thanks for your help.

Upvotes: 16

Views: 113809

Answers (9)

Prashant
Prashant

Reputation: 636

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

Upvotes: 18

SCB
SCB

Reputation: 6149

What are you hoping to achieve here?

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

Upvotes: 25

nikis
nikis

Reputation: 11234

As others pointed, Map by specification can have only one value for a given key. You have 2 solutions:

  • Use HashMap<String, List<String>> to store the data
  • Use Multimap which is provided by 3rd party Google Collections lib

Upvotes: 3

Gospel
Gospel

Reputation: 81

it's impossible,because String is immutable if you use the String as the key of map the same key's value has the same hashcode value.

Upvotes: -1

EvenLisle
EvenLisle

Reputation: 4812

Would you like a concatenation of the two strings?

map.put(key, val);
if (map.containsKey(key)) {
    map.put(key, map.get(key) + newVal);
}

Or would you like a list of all the values for that key?

HashMap<String,List<String>> map = new HashMap<String,List<String>>();
String key = "key";
String val = "val";
String newVal = "newVal";
List<String> list = new ArrayList<String>();
list.add(val);
map.put(key, list);
if (map.containsKey(key)) {
    map.get(key).add(newVal);
}

Upvotes: 5

Moldova
Moldova

Reputation: 1651

You can't directly store multiple values under a single key, but the value associated with a key can be any type of object, such as an ArrayList, which will hold multiple values. For example:

import java.util.ArrayList;
import java.util.HashMap;

public class HashMapList {
    HashMap<String, ArrayList<String>> strings = new HashMap<String, ArrayList<String>>();

    public void add(String key, String value) {
        ArrayList<String> values = strings.get(key);
        if (values == null) {
            values = new ArrayList<String>();
            strings.put(key, values);
        }

        values.add(value);
    }

    public ArrayList<String> get(String key) {
        return strings.get(key);
    }

    public static void main(String[] argv) {
        HashMapList mymap = new HashMapList();

        mymap.add("key", "value1");
        mymap.add("key", "value2");

        ArrayList<String> values = mymap.get("key");
        for (String value : values) {
            System.out.println(value);
        }
    }
}

Upvotes: 0

Sankozi
Sankozi

Reputation: 568

You could use Map<String, Collection<String>> but adding and removing values would be cumbersome . Better way is using guava Multimap - a container that allows storing multiple values for each key.

Upvotes: 0

Fellrond
Fellrond

Reputation: 231

As described in Map interface documentation Map contains a set of keys, so it is not capable of containing multiple non-unique keys.

I suggest you to use lists as values for this map.

Upvotes: 1

M Sach
M Sach

Reputation: 34424

Store value as list under map So if key is test and there are two values say val1 and val2 then key will be test and value will be list containing val1 and val2

But if your intention is to have two separate entries for same key, then this is not Map is designed for. Think if you do map.get("key"), which value you expects

Upvotes: 0

Related Questions