Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending data to Map in Java

Tags:

java

hashmap

map

I have a Map

Map<Integer, List<Object>> entireData;

Now to this I'm adding some data using putAll like

entireData.putAll(someData);

where someData returns Map<Integer, List<Object>>

Now, I have another line which says

entireData.putAll(someMoreData);

which also returns Map<Integer, List<Object>>, but by doing this it over-writes the content of the existing entireData, how do I append?

like image 452
Vivek Avatar asked Jan 06 '11 09:01

Vivek


People also ask

How do you add an element to a HashMap in Java?

To add elements to HashMap, use the put() method.

How do I put multiple values on a map?

If this is an application requirement, the three best ways to solve the 'multiple values per key in a map in Java' problem are: Stick with the standard APIs and add a collection class like a 'Vector' or 'ArrayList' to your map or set. Use the MultiMap and MultiValueMap classes from the Apache Commons library.

How do you add something to a HashMap?

put() method of HashMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to into a particular map. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole.


2 Answers

First line of the Java Map Class Reference:

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

like image 173
trojanfoe Avatar answered Sep 20 '22 12:09

trojanfoe


You want a Multimap from Google Guava. Rewriting your example with Guava Multimap:

ListMultimap<Integer, Object> entireData = ArrayListMultimap.create();

entireData.get(key) returns a List<Object>. putAll will not override old keys but will append the values of those keys to the existing values. This is also much nicer than dealing with initializing the List instances yourself.

like image 35
sjr Avatar answered Sep 21 '22 12:09

sjr