anonuser1234
anonuser1234

Reputation: 533

Comparing multiple fields of 2 list of different objects

I have two objects, both have 4 similar fields that I need to compare and I get them from different sources as a list of objects. I want to make sure that there is at least one matching object in both list, as in they have the exact same fields. The issues is that they can be in different order. I have this code where I have two for loops

for(Object1 object1 : list1){
    bool match = false;
    for(Object2 object2 : list2){
        if(object1.getField1().equal(object2.getField1()) && etc etc..){
             match = true;
             break;
        }
    }
    if(!match)
        return false
}
return true;

Basically I iterate through all of list2 to see if there is at least one match row that has all the same fields in object1, if there is none, then I return false, if there is a matching row then I move on to the next row until I check all of the rows in list1.

I do not like this way of checking and I was wondering if there is an easier way of checking this. I have heard of using Stream in java 8 but I cannot think of a way of using in this scenario. Any help would be greatly appreciated, thank you.

Upvotes: 1

Views: 1563

Answers (1)

Yegor Babarykin
Yegor Babarykin

Reputation: 705

You can use this:

boolean isMatchs = list1.stream()
        .allMatch(el1 -> list2.stream().anyMatch(el2 -> equals(el1, el2)));

with static method equals like this:

static boolean equals(Object1 a, Object2 b) {
    return Objects.equals(a.getField1(), b.getField1());// && ...
}

Upvotes: 2

Related Questions