简体   繁体   中英

How to add a value to a list of values for a single key in a hashmap (Java)

I have written this:

HashMap<String, String> map1 = new HashMap<String, String>();
Map<String, ArrayList<String>> map2 = new HashMap<String, ArrayList<String>>();

i am trying to allow more then 1 value for each key in a hashmap. so if the first key is '1', i want to allow '1' to be paired with values '2' and '3'.

so it be like:

1 --> 2
|--> 3

but when I do:

map2.put(key, value);

it gives error that says "incompatible types" and it can not be converted to ArrayList and it says the error is at the value part of the line.

If you are using Java 8, you can do this quite easily:

String key = "someKey";
String value1 = "someValue1";
String value2 = "someValue2";

Map<String, List<String>> map2 = new HashMap<>();
map2.computeIfAbsent(key, k -> new ArrayList<>()).add(value1);
map2.computeIfAbsent(key, k -> new ArrayList<>()).add(value2);
System.out.println(map2);

The documentation for Map.computeIfAbsent(...) has pretty much this example.

In map2 you need to add ArrayList (you declared it as Map<String, ArrayList<String>> - the second one is the value type) only, that's why it gives you incompatible types .

You would need to do initialize the key with an ArrayList and add objects to it later:

if (!map2.containsKey(key)) {
    map2.put(key, new ArrayList<String>());
}
map2.get(key).add(value);

Or you could use Multimap from guava, then you can just map2.put and it won't overwrite your values there but add to a list.

It is all because standard Map implementations in java stores only single pairs (oneKey, oneValue). The only way to store multiple values for a particular key in a java standard Map is to store "collection" as value, then you need to access this collection (from Map) by key, and then use this collection "value" as regular collection, in your example as ArrayList. So you do not put something directly by map.put (except from creating the empty collection), instead you take the whole collection by key and use this collection.

You need something like Multimap, for example:

      public class Multimap<T,S> {
         Map<T, ArrayList<S>> map2 = new HashMap<T, ArrayList<S>>();

         public void add(T key, S value) {
           ArrayList<T> currentValuesForGivenKey = get(key);
           if (currentValuesForGivenKey == null) {
              currentValuesForGivenKey = new ArrayList<T>();
              map2.get(key, currentValuesForGivenKey);
           }
           currentValuesForGivenKey.add(value);
         }

         public ArrayList<S> get(T key) {
           ArrayList<String> currentValuesForGivenKey = map2.get(key);
           if (currentValuesForGivenKey == null) {
              currentValuesForGivenKey = new ArrayList<S>();
              map2.get(key, currentValuesForGivenKey);
           }
           return currentValuesForGivenKey;
         }

        }

then you can use it like this:

Multimap<String,String> map2 = new Multimap<String,String>();

map2.add("1","2");
map2.add("1","3");
map2.add("1","4");

for (String value: map2.get("1")) {
  System.out.println(value);
}

will print:

2
3
4

You are little bit away from what you are trying to do.

Map<String, ArrayList<String>> map2 = new HashMap<String, ArrayList<String>>();

this will allow only String as key and an ArrayList as value. So you have to try something like:

 ArrayList<String> value=new ArrayList<String>();
 value.add("2");
 value.add("3");
 map2.put("1", value);

When retrieving you also have to follow ans opposite procedure.

 ArrayList<String> valueTemp=map2.get("1");

then you can iterate over this ArrayList to get those values ("2" and "3");

Try like this. //use list or set.. but set avoids duplicates

Map<String, Set<String>> map = new HashMap<>();
 Set<String> list = new HashSet<>();

// add value to the map

 Boolean b = map.containsKey(key);
                if (b) {
                    map.get(key).addAll(list);
                } else
                    map.put(key, list);
            }

You can not add different values in same key in Map. Map is override the value in that key. You can do like this way.

Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
ArrayList<String> list=new ArrayList<String>();
 list.add("2");
 list.add("3");
 map.put("1", list);

first add value in array list then put into map.

it gives error that says "incompatible types" and it can not be converted to ArrayList and it says the error is at the value part of the line.

because, it won't automatically convert to ArrayList .

You should add both the values to list and then put that list in map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM