2013-03-11 89 views
0

我有一個哈希映射和值。現在我想將地圖中的值設置爲鍵和鍵作爲值。任何人都可以提出任何想法HashMap鍵和值

我的地圖是

Map<String, String> col=new HashMap<String, String>(); 
col.put("one","four"); 
col.put("two","five"); 
col.put("three","Six"); 

現在我想創建另一個地圖,並把它在其他的方式如我上面說。即,

Map<String, String> col2=new HashMap<String, String>(); 
col.put("five","one"); 
col.put("four","two"); 
col.put("Six","three"); 

有人有想法嗎?謝謝

回答

1

假設你的值在你的hashmap中是唯一的,你可以這樣做。

// Get the value collection from the old HashMap 
Collection<String> valueCollection = col.values(); 
Iterator<String> valueIterator = valueCollection.iterator(); 
HashMap<String, String> col1 = new HashMap<String, String>(); 
while(valueIterator.hasNext()){ 
    String currentValue = valueIterator.next(); 
    // Find the value in old HashMap 
    Iterator<String> keyIterator = col.keySet().iterator(); 
    while(keyIterator.hasNext()){ 
      String currentKey = keyIterator.next(); 
      if (col.get(currentKey).equals(currentValue)){ 
       // When found, put the value and key combination in new HashMap 
       col1.put(currentValue, currentKey); 
       break; 
      } 
    } 
} 
+0

謝謝。我知道了 – 2013-03-11 11:08:13

+0

-1:不必要的n²複雜性。 – Boann 2013-03-11 11:39:34

+0

@Boann我同意。 'entrySet'方法並沒有打擊我。 – 2013-03-11 11:57:31

0

創建另一個Map並通過遍歷鍵/值一個接一個,把在新Map。最後刪除舊的。

2

像這樣:

Map<String, String> col2 = new HashMap<String, String>(); 
for (Map.Entry<String, String> e : col.entrySet()) { 
    col2.put(e.getValue(), e.getKey()); 
}