3

让我们举个例子,您有两个具有相同值的员工对象,如下所示。

Employee employee1 = new Employee(1001, "Sam", 20000);
Employee employee2 = new Employee(1001, "Sam", 20000);
if(doCompareEmployees(employee1, employee2)){
    System.out.println("Both employee objects are same.");
}else{
    System.out.println("Both employee objects are not same.");
}

//Here is compare method using java 8.

private boolean doCompareEmployees(Employee employee1, Employee employee2) {
int returnValue = Comparator.comparing(Employee::getID)
    .thenComparing(Employee::getName)
    .thenComparing(Employee::getSalary)
    .compare(employee1, employee2);
    if (returnValue != 0){
        return false;
    }   
    return true;
}

我想知道,还有其他更好的方法来比较 Java 8 中的对象吗?

4

2 回答 2

4

如果您不想在对象上定义排序,通常您不会编写 Comparator。

为类定义相等的典型方法是同时定义一个equals()和一个hashCode()方法。要实现hashCode(),Objects.hash()可以提供帮助(从 Java 7 开始存在)。

public int hashCode() {
    return Objects.hash(id, name, salary);
}

public boolean equals(Object o) {
    if (o == this) return true;
    if (o == null || o.getClass() != getClass()) return false;
    Employee e = (Employee) o;
    return id == e.id && salary == e.salary && Objects.equals(name, e.name);
}

尽管 lambda 表达式在某些情况下允许编写非常优雅的代码,但它们并不是每个问题的最佳解决方案。

于 2017-12-06T16:23:45.697 回答
1

您可以检查此LambdaEquals实用程序。但是,作为一个好习惯,您应该坚持使用等式覆盖以获得最佳性能。覆盖“equals”方法可能比 Comparator.comparing 更快。

下面是与 Hoopje 提供的相同的覆盖示例,只是略有不同。

在 Employee 类中重写 equals 方法:

public class Employee {
.....
.....
@Override
public boolean equals(Object o) {
     if(super.equals(o)) {
         return true;
     }
    if(!(o instanceof Employee)) {
        return false
    }

    Employee otherEmployee = (Employee) o;

    return 
        id == otherEmplyee.getId &&
        name == otherEmplyee.getName() &&
        salary == otherEmplyee.getSalary;

}


//Use the equal method
if(emp1.equals(emp2) {
    //do something
}
于 2017-12-06T17:42:00.343 回答