2013-03-11 175 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()); 
}