sbsekar
sbsekar

Reputation: 67

How to add multiple values to the same key in Map

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.

Upvotes: 3

Views: 4452

Answers (2)

phury
phury

Reputation: 2213

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);

Upvotes: 3

StormeHawke
StormeHawke

Reputation: 6207

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]); 
}

Upvotes: 5

Related Questions