Adding data to a Map in Java

I have a card

Map<Integer, List<Object>> entireData;

Now I am adding some data using putAll like

entireData.putAll(someData);

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

Now I have another line that says

entireData.putAll(someMoreData);

which also returns Map<Integer, List<Object>>, but by doing this, it overwrites the contents of existing integer Data, how can I add?

+3
source share
5 answers

The first line of the Java Map class reference:

An object that maps keys to values. the card cannot contain duplicate keys; each key can display no more than one value.

+5
source

You want Multimap from Google Guava , Overwrite your example with Guava Multimap:

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

entireData.get(key) a List<Object>. putAll , . , List.

+6
for (Integer key : someMoreData.keySet())
{
    if (entireData.containsKey(key))
    {
        entireData.get(key).addAll(someMoreData.get(key));
    }
    else
    {
        entireData.put(key, someMoreData.get(key));
    }
}
+4

. someMoreData , entireData, i.e . .

someMoreData , entireData,

 for(Integer key: someMoreData.keySet()){
       if(entireData.get(key)!=null)
           entireData.get(key).addAll(someMoreData.get(key));
       else
           entireData.put(key,someMoreData.get(key));
 }
+2

Java , . , Multi-Map (, ).

The most popular versions can be found in two open source versions, Google Guava and Apache Commons / Collections .

Guava example:

final Multimap<Integer, String> mmap =
    Multimaps.newSetMultimap(
        Maps.<Integer, Collection<String>> newHashMap(),
        new Supplier<Set<String>>(){

            @Override
            public Set<String> get(){
                return Sets.newHashSet();
            }
        });
mmap.put(1, "foo");
mmap.put(1, "bar");
System.out.println(mmap.get(1));

Conclusion:

[foo, bar]

Example Commons Collections:

final MultiMap mmap = new MultiHashMap();
mmap.put(1, "foo");
mmap.put(1, "bar");
System.out.println(mmap.get(1));

Conclusion:

[foo, bar]

As you can see, the version of Commons Collections is much simpler, but it is also less efficient, and in the current version it does not support Java 1.5 generators. Therefore, I will go with Guava.

+2
source

Source: https://habr.com/ru/post/1783820/


All Articles