2016-07-26 92 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