Search code examples
javaperformancelistcollectionscomparison

The best way to compare two very large lists


I have two very large lists. Let say a few millions of elements. Both list are already sorted in the same way. Now I need to check that both lists are equal. What is the best way to do this? For now my idea is to compare line to line using Assert.assertEquals.

for(int i=0;i<Math.max(list1.size(),list2.size()),i++){

Assert.assertEquals(list1.get(i),list2.get(i));
}

Unfortunately I'm worry about the performance of this solution if the lists have many millions of objects. Additionally if the lists are not equal then I need to know where the discrepancies are.

Is there a better, faster and confident solution to do this?


Solution

  • In the end it's an O(n) operation if the lists are equal. So I would go the easy way and simply use:

    Assert.assertEquals(list1, list2);
    

    which will rely on List::equals to compare the lists - I doubt you can be more efficient than that, unless you have specific information about the list content.

    If the lists are not equal you should get an exception that shows the difference.