2017-01-25 35 views
0

我有以下方法,我想比較2個哈希映射 :map1和map2。比較Java中的2個哈希映射

每一個HashMap具有:

key: string.

value: ArrayList<String> 

我所試圖做的是檢查,如果兩個包含HashMap是相等的

public boolean compareT(HashMap map1, HashMap map2) { 

     Iterator entriesH = map1.entrySet().iterator(); 
     Iterator entriesE = map2.entrySet().iterator(); 

     if (map1.size() == map2.size()) { 
      while (entriesE.hasNext() && entriesH.hasNext()) { 
       Map.Entry eEntry = (Map.Entry) entriesE.next(); 
       Map.Entry hEntry = (Map.Entry) entriesH.next(); 
      } 
     } 
} 

編輯

以下地圖應該返回RN TRUE:

map1: 
key: key1, value: v1, v6, v3, v2 
key: key2, value: b1, b6, b2, b7 


map2: 
key: key1, value: v6, v3, v2, v1 
key: key2, value: b6, b1, b7, b2 
+2

那麼這有什麼問題? – csmckelvey

+4

即使所有的鍵/值都相同,也不能保證兩張地圖會以相同順序返回條目。 – biziclop

+2

'map1.equals(map2)'將檢查這兩個映射是否包含映射到相同值的相同鍵,而不管順序如何(由Map :: equals指定)(https://docs.oracle.com /javase/8/docs/api/java/util/Map.html#equals-java.lang.Object-) – yshavit

回答

0
  1. 檢查尺寸均爲地圖,你做
  2. 檢查所有的按鍵都是這兩個地圖一樣,map1.equals(MAP2)
  3. 如果同所有的鍵都是一樣的,然後開始一次抓住一個鍵並比較數組列表。

如果您從未獲得map1.get(key).get(index)!= map2.get(key).get(index),那麼您可以確定地圖是相同的。

僞碼

if(map1.size == map2.size && map1.equals(map2)) 
    //in here means the keys are the same 
    allkeys = map1's keys 
    for (string key : allKeys) 
     //now we need to loop through the arraylists 
     map1Arraylist = map1.get(key) 
     map2Arraylist = map2.get(key) 
     //check the sizes are the same if not return false right away 
     if(map1Arraylist.size != map2Arraylist.size) return false; 
     //if we got to here we now must check each index is the same 
     for(index = 0; index < map1Arraylist.size; index++) 
      //if a single index of the arraylists don't match up we return false 
      if(map1Arraylist.get(index) != map2Arraylist.get(index)) 
       return false; 

    //if we get out of all the above logic then we have the same maps 
    return true; 
else return false; 
+0

你能分享一個代碼示例嗎? – user9524367

+1

這個僞代碼應該是非常明顯的,你可以很容易地將它實現到你現有的比較方法@ user9524367 –

1

我應該下令每一個鍵的值之前,我對它們進行比較?

您的值是ArrayList對象。 ArrayLists(或任何其他List實現)只有在它們具有相同的條目)時才被認爲是相等的。

也許你可以使用某種java.util.Set來代替。

+1

問題中沒有'ArrayList',但'Set'應該這樣做。 – cybergen