2016-07-26 37 views
1

它是一个初学者的问题,我想交换密钥与值,反之亦然HashMap。这是迄今为止我尝试过的。交换密钥与值,反之亦然HashMap

import java.util.HashMap; 
import java.util.Map; 

class Swap{ 
    public static void main(String args[]){ 

     HashMap<Integer, String> s = new HashMap<Integer, String>(); 

     s.put(4, "Value1"); 
     s.put(5, "Value2"); 

     for(Map.Entry en:s.entrySet()){ 
      System.out.println(en.getKey() + " " + en.getValue()); 
     } 
    } 
} 

回答

1

如伊兰的建议,我写了简单的演示,用另一个hashmap交换hashmap的key和value。

import java.util.HashMap; 
import java.util.Map; 

class Swap { 
    public static void main(String args[]) { 

     HashMap<Integer, String> s = new HashMap<Integer, String>(); 

     s.put(4, "Value1"); 
     s.put(5, "Value2"); 

     for (Map.Entry en : s.entrySet()) { 
      System.out.println(en.getKey() + " " + en.getValue()); 
     } 

     /* 
     * swap goes here 
     */ 
     HashMap<String, Integer> newMap = new HashMap<String, Integer>(); 
     for(Map.Entry<Integer, String> entry: s.entrySet()){ 
      newMap.put(entry.getValue(), entry.getKey()); 
     } 

     for(Map.Entry<String, Integer> entry: newMap.entrySet()){ 
      System.out.println(entry.getKey() + " " + entry.getValue()); 
     } 
    } 
} 
+0

伟大的作品给我 –

6

您需要新的Map,因为示例中的键和值有不同的类型。

在Java 8这可以通过创建原始Map的条目Stream和使用toMapCollector生成新Map很容易实现:

Map<String,Integer> newMap = 
    s.entrySet().stream() 
       .collect(Collectors.toMap(Map.Entry::getValue,Map.Entry::getKey)); 
+0

这是非常简单和优雅,但我使用的是早期版本。 –

+1

@HiteshkumarMisro那么,在早期的Java版本中,您必须创建一个新的'Map',使用循环遍历原始Map的entrySet(),并调用'newMap.put(entry.getValue(),entry)。 getKey())'为每个条目。 – Eran