[英]two HashMap iteration
我有兩個HashMap,可以用以下代碼迭代兩個hashmap
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
String firstVal = pairs.getValue();
}
Iterator it2 = mp2.entrySet().iterator();
while (it2.hasNext()) {
Map.Entry pairs2 = (Map.Entry)it.next();
String SecondVal = pairs2.getValue();
}
myFunction(firstVal, SecondVal)
有沒有在不使用兩個循環的情況下同時迭代兩個哈希圖的方法?
當前,我有一個接受兩個參數的方法,每個參數值存儲在第一和第二個哈希圖中。 我必須先迭代哈希然后再迭代才能獲取值。 我認為一定有很好的方法可以做到,但我不知道:(
PS:以上代碼可能存在一些錯誤,因為這只是解釋我的問題的示例。 每個迭代器都是原始程序中的一個方法,並接受一個參數。 我無法復制過去的實時函數,因為它們非常龐大!
將2個映射的值放入列表,然后循環列表:
//Merge 2 values of maps to a list
List<String> mergedList = new ArrayList<String>();
mergedList.addAll(map1.values());
mergedList.addAll(map2.values());
int size = map1.size() < map2.size() ? map1.size() : map2.size();
for(int i=0; i < size; i++){
myFunction(mergedList.get(i), mergedList.get(map1.size() + i));
}
您的代碼看起來不錯。 只需將while循環用作內部循環和外部循環,即可在兩個HashMap上進行迭代。 在第二個while循環中,您可以調用函數以執行所需的操作。
while loop (iterate first hashmap)
second while loop(iterate second hashmap)
call your function here and pass values
Map.Entry pairs;
String firstValue = null;
String secondValue = null;
while(it.hasNext() || it2.hasNext()){
if (it.hasNext()){
pairs = (Map.Entry)it.next();
firstValue = pairs.getValue();
}
if (it2.hasNext(){
pairs = (Map.Entry)it2.next();
secondValue = pairs.getValue();
}
if (firstValue != null && secondValue != null){
yourMethodHere();
firstValue = null;
secondValue = null;
}
}
我認為您正在嘗試執行以下操作:
if (mp.size() != mp2.size()) {
throw SomeException("mismatched parameters");
}
Iterator it = mp.entrySet().iterator();
Iterator it2 = mp2.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
String firstVal = pairs.getValue();
Map.Entry pairs2 = (Map.Entry)it.next();
String secondVal = pairs2.getValue();
myFunction(firstVal, secondVal);
}
請注意,對一對HashMaps中的條目進行並行迭代是狡猾的。 HashMap的條目將按鍵“排列”的唯一情況是兩個HashMap具有相同的鍵和相同的哈希碼,並且從新分配的HashMap開始以相同的順序填充它們。
因此,我認為您確實需要執行以下操作。
if (mp.size() != mp2.size()) {
throw SomeException("mismatched parameters");
}
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
String firstVal = pairs.getValue();
String SecondVal = mp2.get(pairs.getKey());
myFunction(firstVal, SecondVal);
}
如果Map對象本身是並行的,那么更好的解決方案可能是創建自定義Class而不是使用Map。 正如某些util對象中已經提到的那樣,可以保證Maps中的迭代順序(另一種是LinkedHashMap)。 盡管沒有將對象當作數組或列表那樣使用,但這並沒有授予開發人員許可。
除非它們具有相同的鍵集,否則您不能在一個循環中迭代兩個映射。 我不知道您如何找到firstVal
和SecondVal
,似乎有點模棱兩可。 也許您可以通過Map.get()
獲得這兩個值?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.