Reputation: 67
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
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
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