[英]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.