如何比较 Java 8 中的两个对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47656098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:43:35  来源:igfitidea点击:

How to compare two objects in Java 8

javajava-8compareobject

提问by Sabarish.K

Lets take an example you have two employee object having same values as follows.

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

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;
}

I would like know about, is there any other better approach to compare objects in Java 8 ?

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

回答by Hoopje

If you do not want to define an ordering on your objects, normally you would not write a Comparator.

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

The typical way to define equality for a class, is to define both an equals()and a hashCode()method. To implement hashCode(), Objects.hash()can help (present since Java 7).

为类定义相等性的典型方法是定义一个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);
}

Although lambda expressions allow to write very elegant code in some cases, they are not the best solution for each problem.

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

回答by Octtavius

You can check this LambdaEqualsutility. However, as a good habit, you should stick to the equals overriding for the best performance. Overriding the "equals" method could be faster than Comparator.comparing.

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

Below is the same example of override as Hoopje provided, just slightly differs.

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

In the Employee class override the equals method:

在 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
}