In a unit test, I want to verify that two lists contain the same elements. The list to test is build of a list of Person
objects, where one field of type Stri
This is how I solved the equality of 2 lists of Person
public class Person {
private String name;
//constructor, setters & getters
@Override
public boolean equals(Object o) {
if(this == o) return true;
if(o == null || getClass() != o.getClass()) return false
Person p = (Person) o;
return name.equals(p.name);
}
@Override
public int hashCode() { return Objects.hash(name);}
}
// call this boolean method where (in a service for instance) you want to test the equality of 2 lists of Persons.
public boolean isListsEqual(List givenList, List dbList) {
if(givenList == null && dbList == null) return true;
if(!givenList.containsAll(dbList) || givenList.size() != dbList.size()) return false;
return true;
}
// You can test it in a main method or where needed after initializing 2 lists
boolean equalLists = this.isListsEqual(givenList, dbList);
if(equalLists) { System.out.println("Equal"); }
else {System.out.println("Not Equal");}
I hope this can help someone in need.