简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM