Map implementation with duplicate keys

后端 未结 18 1902
暗喜
暗喜 2020-11-22 15:23

I want to have a map with duplicate keys.

I know there are many map implementations (Eclipse shows me about 50), so I bet there must be one that allows this. I know

18条回答
  •  别跟我提以往
    2020-11-22 15:52

    I had a slightly different variant of this issue: It was required to associate two different values with same key. Just posting it here in case it helps others, I have introduced a HashMap as the value:

    /* @param frameTypeHash: Key -> Integer (frameID), Value -> HashMap (innerMap)
       @param innerMap: Key -> String (extIP), Value -> String
       If the key exists, retrieve the stored HashMap innerMap 
       and put the constructed key, value pair
    */
      if (frameTypeHash.containsKey(frameID)){
                //Key exists, add the key/value to innerHashMap
                HashMap innerMap = (HashMap)frameTypeHash.get(frameID);
                innerMap.put(extIP, connName+":"+frameType+":"+interfaceName);
    
            } else {
                HashMap innerMap = new HashMap();
                innerMap.put(extIP, connName+":"+frameType+":"+interfaceName);
                // This means the key doesn't exists, adding it for the first time
                frameTypeHash.put(frameID, innerMap );
            }
    }
    

    In the above code the key frameID is read from a input file's first string in each line, the value for frameTypeHash is constructed by splitting the remaining line and was stored as String object originally, over a period of time the file started having multiple lines (with different values) associated with same frameID key, so frameTypeHash was overwritten with last line as the value. I replaced the String object with another HashMap object as the value field, this helped in maintaining single key to different value mapping.

提交回复
热议问题