gpt4 book ai didi

collections - 比较两个列表时忽略字段

转载 作者:行者123 更新时间:2023-12-03 19:35:36 26 4
gpt4 key购买 nike

我有两个 Person 对象列表。

Person class has the below attributes
String Name,
Integer Age,
String Department,
Date CreatedTime,
String CreatedBy

当我比较我的列表是否相等时,我不想比较 CreatedTime 和 CreatedBy 字段。

如何使用 Java 8 比较两个列表的相等性并忽略 CreatedTime、CreatedBy 字段进行比较?

最佳答案

你甚至不需要 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);

编辑:

关注您的评论:

I need this form of comparison only for test purposeses . In my production code I would like to retain equals and hashcode to compare all fields



你可以像这样定义一个自定义的 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);

关于collections - 比较两个列表时忽略字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49557913/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com