javalistlist-comparison

Comparing two list of objects in Java


I have two list of Student Objects(listA & listB) which were formed by querying from two different databases. I need to iterate one list and need to make sure it is not present in the other list.

I have used the below comparison code for the same i.e overwritten the equals method and compared using for loops.

Say List A & List B could have 5000 rows each, can you suggest if there are better ways to implement this?

Comparison code:

for (Student dataA:listA) {
    for (Student dataB:listB) {
        if(dataB.equals(dataA))
            break;                                              
    }
}

Student Object:

public class Student {
    int A;
    int B;
    String C;   

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (obj == null || obj.getClass() != this.getClass()) {
            return false;
        }
        Student student = (Student) obj;
        return A == student.A && B == student.B && C.equals(student.C);
    }
}

Edit Note: ListA & ListB can have different number of rows


Solution

  • I would suggest you the retainAll method:

    List<Student> listC = new ArrayList();
    listC.addAll(listA);
    listC.retainAll(listB);   //now listC contains all double students
    

    But you should still override the equals method