mardi 17 décembre 2019

How to Compare Two Lists of Java Objects by Property Values

I want to assert that two lists of objects of the same type are the same by the property values of that object. For example, I have two lists of Person objects which have first, last, and middle name properties. Each Person object has method setters and getters for each of these properties (java beans), and the constructor contains no parameters.

Let's assume here that I already have a list of two People called existingPersonList which has the following properties: Existing person1: firstName = Bob, lastName = Smith Existing person2: firstName = Sue, middleName = K., lastName = White

I want to compare the objects, so the approach I have taken is to create new ones to compare against:

Person person1 = new Person(); 
Person person2 = new Person();
List<Person> personList = new ArrayList<>();
person1.setFirstName("Bob");
person1.setLastName("Smith");
person2.setFirstName("Sue");
person2.setMiddleName("K.");
person2.setLastName("White");
personList.add(person1);
personList.add(person2);

What I'm currently doing is iterating through both lists with for loops and using the Hamcrest method samePropertyValue(personList.get(i)).matches(existingPersonList.get(j)) to find a match and assertTrue, however this is very inefficient for large lists.

Is there a better way to go about doing this? Or at very least directly compare the two lists instead of iterating through?

Aucun commentaire:

Enregistrer un commentaire