简体   繁体   English

如何在hashmap b中找不到hashmap a中的值

[英]How can I find if value in hashmap a does not exist in hashmap b

I have two different hashmaps with query results, though the 2 hashmaps are different sizes hashmap, and I'm trying to find records that exist in hashmap A that don't exist in hashmap B. 我有两个不同的查询结果的哈希图,虽然2个哈希图是不同大小的hashmap,我正在尝试查找hashmap A中不存在的记录。

I'll post my code so far; 到目前为止我会发布我的代码; I did the comparison via sql and I get the result I want, but when I tried to put it in code I'm not successful. 我通过sql进行了比较,得到了我想要的结果,但是当我试图把它放在代码中时,我没有成功。 I hope you can point me in the right direction. 我希望你能指出我正确的方向。 Thanks in advance 提前致谢

HashMap<Integer, HashMap<String, Object>> mapA = new HashMap<>();
HashMap<Integer, HashMap<String, Object>> mapB = new HashMap<>(); 

int m=0;

for (int j = 0; j < mapA.size(); j++) {
    for (int k = 0; k < mapB.size(); k++) {
        if (!mapA.get(j).get("folio").toString().equals(
             mapB.get(k).get("folio").toString())) {
            m++; // count many records not exist on mapB
        }
    }
}
System.out.println(m);

I'm not sure I understood your approach. 我不确定我理解你的方法。 A more proper way to do that would be (in pseudo code): 更合适的方法是(在伪代码中):

For each element in Hashmap A:
  If !HashmapB.contains(element):
    ++Counter;

There is an error in the logic. 逻辑中存在错误。 You want to find not existing in A records, but incrementing counter everytime when values of both iterating HashMaps don't equal (you will get much greater m in this case). 您希望找到A记录中不存在,但每次迭代HashMaps的值不相等时都会递增计数器(在这种情况下,您将获得更大的m)。 Your code should look like. 你的代码应该是这样的。

for (int j = 0; j < mapA.size(); j++) {
    boolean found=false;
    for (int k = 0; k < mapB.size(); k++) {
        if (mapA.get(j).get("folio").toString().equals(
            mapB.get(k).get("folio").toString())) {
            found=true;   
            break;
        }
    }

    if (!found){
       m++; // count many records not exist on mapB
    }
}

Also there is additional possible error. 还有其他可能的错误。 In general case you have to make comparision not after toString method but compare objects (I think you didn't ovverite toString method of your objects to return valid identifier to compare them. And in most cases it will return not what you need. Or in other words you should ovveride equals methods of all you possiblle objects in hashmaps and use next code for comparision: 在一般情况下,你不得不在toString方法之后进行比较,而是比较对象(我认为你没有对象的ovverite toString方法返回有效的标识符来比较它们。在大多数情况下,它将不会返回你需要的东西。或者在换句话说,你应该使用ovveride等于散列图中所有可能对象的方法,并使用下一个代码进行比较:

mapA.get(j).get("folio").equals(mapB.get(k).get("folio"))

In your case (with toString) comparision can return always false, because typical toString return class and ID of the objects. 在你的情况下(使用toString),比较可以返回false,因为典型的toString返回对象的类和ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM