简体   繁体   中英

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.

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. 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). 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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