2012-10-06 28 views
2

我被困在如何將map1中的鍵值對轉移到map2中(僅當每個鍵在map1中具有唯一值)。如何在地圖中刪除重複的鍵值對

比方說,我有以下地圖:

  • MAP1:[1,2] [2,4] [4,4]
  • MAP2:[1,2] [2,4]

我假設算法將是:

  1. 循環通過第一映射條目。
  2. 添加一個鍵到map2。
  3. 將值添加到一個檢查map2的值的集合
  4. 如果值重複,則該值不會添加到集合中,並忽略將其相應的鍵添加到map2。

代碼片段:

public static <K,V> Map<K,V> unique (Map<K,V> m) { 
    Map<K,V> newMap = new ArrayMap<K,V>(); 

    //Remember all values in the newMap. 
    Set<V> holding = new ArraySet<V>(newMap.values()); 

    for (Map.Entry<K, V> graphEntry : m.entries()) { 
    //not sure. 
    } 

    return newMap; 
} 

是我如何它應該在正確的軌道上進行想法?很遺憾在這裏。

+0

是否要將map1中的對添加到map2並避免將map2中的值覆蓋? – svz

+0

你可以發佈你的請求出鍋嗎? – elyashiv

+0

爲什麼你的算法不生成map1的{1:2,4:4}?你爲什麼選擇'2'?這不重要嗎? – cheeken

回答

3

Map<K, V>創建一個Map<V, K>,當且僅當該鍵不在地圖中時纔會添加項目。使用此Map<V, K>,重新創建您的Map<K, V>

public static <K, V> Map<K, V> createMap(Map<K, V> m) { 
    Map<K, V> map = new HashMap<K, V>(); 
    Map<V, K> tmpMap = new HashMap<V, K>(); 
    for(Map.Entry<K, V> entry : m.entrySet()) { 
     if (!tmpMap.containsKey(entry.getValue())) { 
      tmpMap.put(entry.getValue(), entry.getKey()); 
     } 
    } 
    for(Map.Entry<V, K> entry : tmpMap.entrySet()) { 
     map.put(entry.getValue(), entry.getKey()); 
    } 
    return map; 
} 

如果您需要保留數據的保護者順序,使用LinkedHashMap代替HashMap

0

退房Guava BiMap。這是你所需要的..

雖然你的問題解決了,你可以選擇你想要做什麼就來看看下面的代碼,使用Guava API爲: -

public void removeDuplicateValue() { 
    Map<Integer, String> existingMap = new HashMap<Integer, String>(); 
    existingMap.put(1, "a"); 
    existingMap.put(2, "b"); 

    // Create a new BiMap 
    BiMap<Integer, String> biMap = HashBiMap.create(); 

    for (Integer val: existingMap.keySet()) { 

     // forcePut will add a key-value pair, and overwrite the duplicate value. 
     biMap.forcePut(val, existingMap.get(val)); 
    } 

    // Create Inverse Map for newly created BiMap. 
    BiMap<String, Integer> inverseBiMap = biMap.inverse(); 

    for(String val: inverseBiMap.keySet()) { 
     System.out.println(val + ":" + biMap.get(val)); 
    } 
} 
0

嘗試這一個..

Map<String, String> myMap1 = new TreeMap<String, String>(); 
myMap1.put("1", "One"); 
myMap1.put("2", "Two"); 
myMap1.put("3", "One"); 
myMap1.put("4", "Three"); 
myMap1.put("5", "Two"); 
myMap1.put("6", "Three"); 

Set<String> mySet = new HashSet<String>(); 

for (Iterator itr = myMap1.entrySet().iterator(); itr.hasNext();) 
{ 
    Map.Entry<String, String> entrySet = (Map.Entry) itr.next(); 

    String value = entrySet.getValue(); 

    if (!mySet.add(value)) 
    { 
     itr.remove();    
    } 
} 

    Map<String, String> myMap2 = new TreeMap<String, String>(myMap1); 

    System.out.println("Result :"+myMap2); 

結果:{1 =一個,2 =二,4 =三}