If you want to compare the two lists, you will have to iterate both, but if your lists are sorted and you only want to know, if they are equal or not, then you only have to check each list element of both lists once, which should be much faster in the end for large lists:
public boolean compareTwoLists(List<Person> list1, List<Person> list2) {
// Lists don't have the same size, objects missing in
// list one or two. I your lists have the same size, skip this.
if (list1.size() != list2.size() {
return false;
}
Iterator<Person> it1= list1.iterator();
Iterator<Person> it2= list2.iterator();
while (it1.hasNext()) {
Person person1 = it1.next();
Person person2 = it2.next();
// Age or name do not match, objects differ, lists are not equal.
if ((!person1.next().getAge().equals(person2.getAge()) || (!person1.getName().equals(person2.getName()))))
return false;
}
// All items are the same.
return true;
}
Furthermore, you could write your method as Comparator
, which makes it more reusable or suitable for sorting, because you can return 0
(lists are equal), -1
(first list is smaller), 1
(first list is larger) or other meanings for your purpose:
class PersonListComparator implements Comparator<List<Person>> {
@Override public int compare(List<Person> list1, List<Person> list2) {
// Your code
}
}
You could also think about overriding the equals(...)
method of the Person
class, if you always compare the name and age. Then, the comparison could be shortened to person1.equals(person2)
in your code.
Alternatively, use the Comparable
interface, which adds a method int compareTo(T object)
to your class that does the same as the Comparator
.