让我们举个例子,您有两个具有相同值的员工对象,如下所示。
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 中的对象吗?