How to compare two objects in Java 8

20.7k Views Asked by At

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 ?

2

There are 2 best solutions below

1
On

If you do not want to define an ordering on your objects, normally you would not write a 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).

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.

5
On

You can check this LambdaEquals utility. 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.

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

In the Employee class override the equals method:

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
}