您甚至不需要 Java-8 的功能来执行此操作,只需像这样覆盖 equals 和 hashCode:
class Person {
String name;
Integer age;
String department;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
if (name != null ? !name.equals(person.name) : person.name != null) return false;
if (age != null ? !age.equals(person.age) : person.age != null) return false;
return department != null ? department.equals(person.department) : person.department == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (age != null ? age.hashCode() : 0);
result = 31 * result + (department != null ? department.hashCode() : 0);
return result;
}
}
然后你可以像这样比较两个给定的列表:
boolean result = firstList.equals(secondList);
编辑:
根据您的评论:
我需要这种形式的比较仅用于测试目的。在我的
生产代码我想保留equals和hashcode来比较
所有字段
你可以像这样定义一个自定义的 equal 方法:
public static boolean areEqual(List<Person> first, List<Person> second) {
Objects.requireNonNull(first, "first list must not be null");
Objects.requireNonNull(second, "second list must not be null");
return first.size() == second.size() &&
IntStream.range(0, first.size()).allMatch(index ->
customCompare(first.get(index), second.get(index)));
}
或者如果您想允许将 null 传递给 areEqual 方法,那么稍作改动就足够了:
public static boolean areEqual(List<Person> first, List<Person> second){
if (first == null && second == null)
return true;
if(first == null || second == null ||
first.size() != second.size()) return false;
return IntStream.range(0, first.size())
.allMatch(index ->
customCompare(first.get(index), second.get(index)));
}
然后是确定两个给定人员对象是否相等的方法:
static boolean customCompare(Person firstPerson, Person secondPerson){
if (firstPerson == secondPerson) return true;
if (firstPerson.getName() != null
? !firstPerson.getName().equals(secondPerson.getName()) : secondPerson.getName() != null)
return false;
return (firstPerson.getAge() != null ? firstPerson.getAge().equals(secondPerson.getAge()) : secondPerson.getAge() == null)
&& (firstPerson.getDepartment() != null
? firstPerson.getDepartment().equals(secondPerson.getDepartment())
: secondPerson.getDepartment() == null);
}
然后这样称呼它:
boolean result = areEqual(firstList, secondList);