两个HashMap迭代

时间:2010-12-26 04:04:54

标签: java data-structures

我有两个HashMaps,我可以使用以下代码迭代这两个哈希映射

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)

无论如何在不使用两个循环的情况下同时迭代两个哈希映射?

目前,我有一个接受两个参数的方法,每个参数值都存储在第一个和第二个hashmap中。我必须迭代第一个哈希然后第二个来获取值。我认为必须有一个好方法,但我不知道:(

P.S:上面的代码可能有一些错误,因为这只是解释我的问题的一个例子。每个迭代器都是原始程序中的一个方法,并接受一个参数。我无法复制过去的实时功能,因为它们是巨大的!

6 个答案:

答案 0 :(得分:3)

将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));
}

答案 1 :(得分:2)

你的代码看起来不错。只需使用while循环作为内部和外部循环来迭代两个HashMaps。在第二个while循环中,您可以调用您的函数来执行您想要的任何操作。

while loop (iterate first hashmap)
    second while loop(iterate second hashmap)
         call your function here and pass values

答案 2 :(得分:1)

    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;
     }
    }

答案 3 :(得分:1)

我认为你要做的是:

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中的条目进行并行迭代是狡猾的。 HashMaps的条目将按键“排列”的情况是两个HashMaps具有相同的密钥具有相同的密钥,并且从新分配的HashMaps开始以相同的顺序填充它们。

因此,我认为你真的需要做这样的事情。

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);
}

答案 4 :(得分:0)

除非它们具有相同的键集,否则不能在一个循环中迭代两个映射。我不知道你如何找到firstValSecondVal,它似乎有点含糊不清。也许你可以通过Map.get()得到这两个值?

答案 5 :(得分:0)

如果Map对象本身是并行的,那么更好的解决方案可能是创建自定义类而不是使用Map。可以保证地图中的迭代顺序,如某些util对象中已经提到的那样(另一个是LinkedHashMap)。但是,这并没有给开发人员许可证,因为它们就像数组或列表一样使用对象。