2013-02-16 107 views
0

我有這個東西,可以說HashMap>有<>「11,name2,name1」和「14,name4,name5」...所以我試圖刪除11首先和所有其數據名稱2和名稱1將被轉移到14。但問題是14自己的原始數據名稱4和名稱5被覆蓋。我想讓他們都在14歲。我應該怎麼做?希望你能幫助我。謝謝。HashMap重複鍵替換java

List<String> oldValue = map.remove(oldKey); 
map.put(newKey, oldValue); 

回答

2

您可以嘗試以下方法。從舊密鑰中提取舊列表。並將列表項添加到新密鑰的列表中。

// remove old key 
    List<String> oldValue = map.remove(oldKey); 
    // add new key with empty list if not exists 
    if(!map.containsKey(newKey)) 
    { 
     map.put(newKey, new LinkedList<String>()); 
    } 
    // new list for new value 
    List<String> newValue = map.get(newKey); 
    // add items from old value to new list 
    for(String s : oldValue){ 
     // eliminate possible duplicates 
     if(!newValue.contains(s)){ 
      newValue.add(s); 
     } 
    } 
+0

哇..感謝你:):..幫助很多 – user2064467 2013-02-16 15:07:49