$show=/label

How To Compare Two Objects In Java 8 For Equality

SHARE:

A quick guide on how to compare two objects for equality in Java 8. Java 8 - Comparison with Lambdas and example on Java 8 Comparator.comparing().

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.

How To Compare Two Objects In Java 8 For Equality


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,


COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: How To Compare Two Objects In Java 8 For Equality
How To Compare Two Objects In Java 8 For Equality
A quick guide on how to compare two objects for equality in Java 8. Java 8 - Comparison with Lambdas and example on Java 8 Comparator.comparing().
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh5otIZ3LakAVKq7Jx2jcJYnWjibs2OjiJvhSCdbkiGPuFjDluRGpDY-GUmbdMa28S6Bj2M4UIpgOR1eb73IIbhNFydHN40pQHc28kZBD-MrSu_C4a1UFoFYh0Ok78F6OjH3nRZsz9cKSA/w640-h369/How+To+Compare+Two+Objects+In+Java+8+For+Equality.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh5otIZ3LakAVKq7Jx2jcJYnWjibs2OjiJvhSCdbkiGPuFjDluRGpDY-GUmbdMa28S6Bj2M4UIpgOR1eb73IIbhNFydHN40pQHc28kZBD-MrSu_C4a1UFoFYh0Ok78F6OjH3nRZsz9cKSA/s72-w640-c-h369/How+To+Compare+Two+Objects+In+Java+8+For+Equality.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/08/how-to-compare-two-objects-in-java-8.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/08/how-to-compare-two-objects-in-java-8.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content