Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add multiple values to the same key in Map

Tags:

java

I have tried as below :

for (Object[] trials: trialSpecs) {
    Object[] result= (Object[]) trials;
    multiValueMap.put((Integer) result[0], new ArrayList<Integer>());
    multiValueMap.get(result[0]).add((Integer)result[1]);
}

But every time the new value is replaced with the old value. I know this is because of new ArrayList<Integer> I used in the code.

But I am not able to replace this block.

like image 964
sbsekar Avatar asked Dec 06 '25 21:12

sbsekar


2 Answers

Only put a new ArrayList() if one is not already present:

for (Object[] trials: trialSpecs) { 
    Object[] result= (Object[]) trials; 
    //Check to see if the key is already in the map:
    if(!multiValueMap.containsKey((Integer) result[0]){
        multiValueMap.put((Integer) result[0], new ArrayList()); 
    }
    multiValueMap.get(result[0]).add((Integer)result[1]); 
}
like image 147
StormeHawke Avatar answered Dec 10 '25 18:12

StormeHawke


java libraries like Guava and Apache propose the Multimap that does exactly that:

With guava:

Multimap<String, String> mhm = ArrayListMultimap.create();
mhm.put(key, "A");
mhm.put(key, "B");
mhm.put(key, "C");
Collection<String> coll = mhm.get(key);

With apache:

MultiMap mhm = new MultiHashMap();
mhm.put(key, "A");
mhm.put(key, "B");
mhm.put(key, "C");
Collection coll = (Collection) mhm.get(key);
like image 20
phury Avatar answered Dec 10 '25 17:12

phury



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!