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?
To add elements to HashMap, use the put() method.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With