![](/img/trans.png)
[英]How to compare two lists of custom objects for some properties using streams in Java?
[英]How to compare two Objects in Java that also have lists in its properties
public class Employee{
int empId;
String empName;
List <EmployeeAddress> empAdd;
// getters & setters
}
public class EmployeeAddress{
String city;
String state;
// getters & setters
}
现在,我制作了两个员工类的对象,并希望将它们进行比较。 由于员工可以有多个地址,因此我在员工类中使用了列表。 在这方面需要帮助
因为不清楚您所说的“比较”是什么意思,所以我想您需要在Employee
类中重写equals
方法。
首先,我建议您看一下SO上的一个有趣问题: 在Java中重写equals和hashCode时应考虑哪些问题?
然后,按照equals
接口List
方法合同:
如果两个列表包含相同顺序的相同元素,则两个列表定义为相等。 此定义确保equals方法可在List接口的不同实现中正常工作。
因此,您可以编写类似以下内容的代码:
@Override
public boolean equals(Object obj) {
Employee e = (Employee) obj;
return this.empId == e.empId && this.empName.equals(e.empName) && this.empAdd.equals(e.empAdd);
}
或者,您可以定义自定义逻辑以进行列表比较...
首先,我建议将List<EmployeeAddress>
更改为Set<EmployeeAddress>
会很好。 这有两种帮助:
话虽如此,但是请确保EmployeeAddress的equals方法也得到了很好的实现,因为Set接口在检测重复项时将要求其正常运行。 然后,您将实现equals为:
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Employee)) {
return false;
}
Employee other = (Employee) obj;
if (this.empAdd == null) {
if (other.empAdd != null) {
return false;
}
} else if (!this.empAdd.equals(other.empAdd)) {
return false;
}
if (this.empId != other.empId) {
return false;
}
if (this.empName == null) {
if (other.empName != null) {
return false;
}
} else if (!this.empName.equals(other.empName)) {
return false;
}
return true;
}
EmployeeAddress类的equals方法的实现应如下所示:
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof EmployeeAddress)) {
return false;
}
EmployeeAddress other = (EmployeeAddress) obj;
if (this.city == null) {
if (other.city != null) {
return false;
}
} else if (!this.city.equals(other.city)) {
return false;
}
if (this.state == null) {
if (other.state != null) {
return false;
}
} else if (!this.state.equals(other.state)) {
return false;
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.