Java 8: More efficient way of comparing lists of different types?

前端 未结 3 1154
情深已故
情深已故 2021-02-05 16:31

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

3条回答
  •  一整个雨季
    2021-02-05 16:58

    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.

提交回复
热议问题