1. Overview
In this article, You'll learn how to compare two objects in the java. In many of the cases, you might need to compare the two same types of objects that are having the same values for all instance variables.
2. Understand the Usecase
Let us create a simple Employee class with instance variables id, name, age for comparing the different objects field by field.
package com.javaprogramto.java8.compare; public class Employee { private int id; private String name; private int age; public Employee(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }This is class is added with now setters, getter methods, and also with a parameterized constructor.
Next, is create two objects with different values and compare them.
3. Compare Two Employee Objects in java
In the below program, Created two Employee objects with different values. Now, our need is to compare two objects that are the same or not.
Every class in java has one parent class that is Object class and it has equals() method to compare two any objects.
package com.javaprogramto.java8.compare; public class CompareTwoObjects { public static void main(String[] args) { // create two Employee Objects Employee e1 = new Employee(100,"Jhon", 30); Employee e2 = new Employee(101,"Amenda", 35); // Compare two employee e1, e2 objects boolean isSame = e1.equals(e2); if(isSame){ System.out.println("e1 and e2 are same objects and have the same values"); } else { System.out.println("e1 and e2 are not same objects"); } } }
Output:
This program compiles and executes successfully.
e1 and e2 are not same objects
When the e1.equals(e2) method is invoked it internally compares two object references but not the values. So it has to have a different address.
let us create a new Employee e3 object with the same values as e1.
Employee e1 = new Employee(100,"Jhon", 30); Employee e3 = new Employee(100,"Jhon", 30); if(e1 == e3){ System.out.println("e1, e3 references are same"); } else { System.out.println("e1, e3 references are different"); } if(e1.equals(e3)){ System.out.println("e1, e3 objects are same"); } else { System.out.println("e1, e3 objects are different"); }Output:
e1, e3 references are different e1, e3 objects are different
The above program produced the output saying both e1, e3 objects are not the same even though both objects are having the same values.
Let us look then at the code inside Object.equals() method and understand its internals.
public boolean equals(Object obj) { return (this == obj); }
equals() method just checks both object references are the same but not the internal field values.
4. Overriding equals() method in the Employee Object
It is good practice to override the equals() method inside the Employee class with the needed comparisons. Those comparisons are to compare the values of id, name, age values.
Let us add the customized logic for object comparisons. This logic will be generated by the IDE's such as Eclipse or IntelliJ Idea tools.
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Employee employee = (Employee) o; return id == employee.id && age == employee.age && Objects.equals(name, employee.name); }
This method logic compares both object's id, name, and age values. If anyone of these properties values are not the same then it returns false. It returns true if all values of the two objects are the same.
Employee e3 = new Employee(100,"Jhon", 30); Employee e1 = new Employee(100,"Jhon", 30); if(e1.equals(e3)){ System.out.println("e1, e3 objects are same"); } else { System.out.println("e1, e3 objects are different"); }
Output:
e1, e3 objects are same
4. Collections API uses hashcode() and equals() Method
We have now checked the objects comparisons manually by calling the equals() method but this is not a good solution for the comparison of the objects.
Because Java Collection API classes internally use equals() and hashcode() methods extensively.
ArrayList uses equlas() method and HashMap uses both hashcode(), equlas() methods internally for objects comparison.
In the next two sections, we will see the example programs on ArrayList and HashMap classes.
5. Object Comparision in ArrayList Example
In the below program, nowhere equals() method is called manually but we called the indexOf() method that internally calls the equals() method. So, our custom equals() method in the Employee class is invoked.
package com.javaprogramto.java8.compare; import java.util.ArrayList; import java.util.List; public class ArrayListComparisions { public static void main(String[] args) { List<Employee> empList = new ArrayList<>(); Employee e1 = new Employee(100,"Jhon", 30); Employee e2 = new Employee(101,"Amenda", 35); Employee e3 = new Employee(102,"Alexa", 40); empList.add(e1); empList.add(e2); empList.add(e3); Employee e4 = new Employee(100,"Jhon", 30); boolean e4Exists = empList.indexOf(e4) > -1; if(e4Exists){ System.out.println("Employee e4 exists in list"); } else{ System.out.println("Emp e4 does not exist in the emp list"); } } }Output:
Employee e4 exists in list
6. Object Comparison in HashMap Example
Let us override the equals() and hashcode() methods in Employee class.
toString() method is to print the values of the object.
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Employee employee = (Employee) o; return id == employee.id && age == employee.age && Objects.equals(name, employee.name); } @Override public int hashCode() { return Objects.hash(id, name, age); } @Override public String toString() { return "Employee{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; }
Create a HashMap object and add a few employee objects as key and value will be the salary of the employee object.
package com.javaprogramto.java8.compare; import java.util.HashMap; import java.util.Map; public class HashMapComparisions { public static void main(String[] args) { // key is employee and value is Salary as long. Map<Employee, Long> empMap = new HashMap<>(); Employee e1 = new Employee(100,"Jhon", 30); Employee e2 = new Employee(101,"Amenda", 35); Employee e3 = new Employee(102,"Alexa", 40); empMap.put(e1, 5000l); empMap.put(e2, 15000l); empMap.put(e3, 25000l); System.out.println("Employee values are : "+empMap); // adding again the same object with different salary Employee e4 = new Employee(100,"Jhon", 30); empMap.put(e4, 35000l); System.out.println("After adding the duplicate employee object with new salary. \nMap Employee objects and values are : "+empMap); boolean e4Exists = empMap.containsKey(e4); if(e4Exists){ System.out.println("Employee e4 exists in list"); } else{ System.out.println("Emp e4 does not exist in the emp list"); } } }
Output:
Employee values are : {Employee{id=100, name='Jhon', age=30}=5000, Employee{id=102, name='Alexa', age=40}=25000, Employee{id=101, name='Amenda', age=35}=15000} After adding the duplicate employee object with new salary. Map Employee objects and values are : {Employee{id=100, name='Jhon', age=30}=35000, Employee{id=102, name='Alexa', age=40}=25000, Employee{id=101, name='Amenda', age=35}=15000} Employee e4 exists in list
Observe the values of HashMap before and after adding the employee values.
Employee e1 and e4 have the same values and added twice with the put() method. But, the salary value is replaced with the new value.
Note: HashMap class put() and containsKey() method internally calls both hashcode() and equlas() methods for object equality.
7. Compare Two Objects in Java 8
How to Find an Element in a List with Java
package com.javaprogramto.java8.compare; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; public class CompareTwoObjectsJava8 { public static void main(String[] args) { System.out.println("Compare with Java 8 API Stream API"); List<Employee> empList = new ArrayList<>(); Employee e1 = new Employee(100,"Jhon", 30); Employee e2 = new Employee(101,"Amenda", 35); Employee e3 = new Employee(102,"Alexa", 40); empList.add(e1); empList.add(e2); empList.add(e3); Employee e4 = new Employee(100,"Jhon", 30); // Stream api boolean e4Exists = Stream.of(e4).anyMatch( e -> empList.contains(e)); if(e4Exists){ System.out.println("Stream checking : Employee e4 exists in list"); } else{ System.out.println("Stream checking : Emp e4 does not exist in the emp list"); } } }Output:
Compare with Java 8 API Stream API Stream checking : Employee e4 exists in list
8. Java 8 - Comparison with Lambdas
The below example uses the Comparator class in Java 8 to compare objects but this comparison is done internally by the Collections.sort() method. But, not at all called in the program manually.
If you are not calling the Collections.sort() method then our comparator logic will not be executed.
To create a custom comparator, user Comparator.comparing() method in java 8 that returns Comparator instance. This newly created comparator instance needs to be passed to the sort() method.
package com.javaprogramto.java8.compare; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class CompareTwoObjectsWithComparator_Comparing { public static void main(String[] args) { System.out.println("Example with Custom comparator with for Sorting"); List<Employee> empList = new ArrayList<>(); Employee e1 = new Employee(100,"Jhon", 30); Employee e2 = new Employee(101,"Amenda", 35); Employee e3 = new Employee(102,"Alexa", 40); empList.add(e1); empList.add(e2); empList.add(e3); Employee e4 = new Employee(103,"Jhon Abraham", 33); empList.add(e4); Comparator<Employee> nameComparator = Comparator.comparing( emp -> emp.getName()); System.out.println("before sorting by name : "+empList); Collections.sort(empList, nameComparator); System.out.println("Sorting by name comparing objects : "+empList); } }
Output:
Example with Custom comparator with for Sorting before sorting by name : [Employee{id=100, name='Jhon', age=30}, Employee{id=101, name='Amenda', age=35}, Employee{id=102, name='Alexa', age=40}, Employee{id=103, name='Jhon Abraham', age=33}] Sorting by name comparing objects : [Employee{id=102, name='Alexa', age=40}, Employee{id=101, name='Amenda', age=35}, Employee{id=100, name='Jhon', age=30}, Employee{id=103, name='Jhon Abraham', age=33}]
9. Conclusion
In this article, You've seen how to compare two objects in java using equals() method of Object class.
And also how equals() and hashcode() method are used widely in the Collection API.
Finally, How to compare and sort the List of employees using the Collections.comparing() method.
All examples are shown in this article are over GitHub,
No comments:
Post a Comment
Please do not add any spam links in the comments section.