gpt4 book ai didi

java - 如何在 Java 8 中比较两个对象

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:02:02 24 4
gpt4 key购买 nike

<分区>

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

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 中的对象?

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