arraylist - how to add a value to a list of values for a single key in a hashmap (Java) -


hi have written this:

hashmap<string, string> map1 = new hashmap<string, string>(); map<string, arraylist<string>> map2 = new hashmap<string, arraylist<string>>(); 

i trying allow more 1 value each key in hashmap. if first key '1', want allow '1' paired values '2' , '3'.

so like:

1 --> 2 |--> 3 

but when do:

map2.put(key, value); 

it gives error says "incompatible types" , can not converted arraylist , says error @ value part of line.

thenk much

if using java 8, can 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 map.computeifabsent(...) has pretty example.


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -