2015-11-05 43 views
-1

我有兩個散列映射:一個包含一個整數鍵和字符串值。比較兩個散列映射和打印交叉點

另一個包含一個整數鍵和浮點值。

代碼

Map<Integer,String> mapA = new HashMap<>(); 
mapA.put(1, "AS"); 
mapA.put(2, "Wf"); 

Map<Integer,Float> mapB = new HashMap<>(); 
mapB.put(2, 5.0f); 
mapB.put(3, 9.0f); 

我的問題是如何使用整數鍵值來比較兩個哈希地圖?我想在鍵值相同時打印位圖值。

+0

我不知道第二部分應該做什麼,但它肯定不會編譯。 – biziclop

+0

你的鑰匙應該是數字嗎?因爲你似乎正在使用字符串 – khelwood

+0

實際上我在我的android應用程序中使用位圖。現在,我以簡單格式更改我的代碼。 – rafeek

回答

0

是的,我得到了解決辦法...

if(mapB.containsKey(position)){ 
      Log.e("bucky",mapB.get(position));} 

位置意味着整數值。

0

通過使用mapB迭代器比較兩個映射中的鍵。

Iterator<Entry<Integer, Float>> iterator = mapB.entrySet().iterator(); 
    while(iterator.hasNext()) { 
     Entry<Integer, Float> entry = iterator.next(); 
     Integer integer = entry.getKey(); 
     if(mapA.containsKey(integer)) { 
      System.out.println("Float Value : " + entry.getValue()); 
     } 
    } 
1

您只需重複上mapA鍵並檢查它是否存在於mapB然後將該值添加到第三mapC例如。

Map<String, float> mapC = new HashMap<String, float>(); 

for (Integer key : mapA.keySet()) { 
    if (mapB.containsKey(key)) { 
     mapC.put(mapA.get(key), mapB.get(key)); 
    } 
} 
0

如果允許修改mapB,則該解決方案爲mapB.keySet().retainAll(mapA.keySet());一樣簡單。

這隻會讓mapB中的對應關鍵字mapA中的條目保留,因爲由keySet()返回的集合由地圖自身支持,所做的任何更改都會反映到地圖中。