Might be a little late, but I was in the same situation like you and ended up creating my own library for exactly your use-case. Since I was forced to come up with a solution myself, I decided to release it on Github, to spare others the hard work. You can find it here: https://github.com/SQiShER/java-object-diff

--- Edit ---

Here is a little usage example based on the OPs code:

SomeClass a = new SomeClass();
SomeClass b = new SomeClass();

a.setProp1("A");
a.setProp2("X");

b.setProp1("B");
b.setProp2("X");

DiffNode diff = ObjectDifferBuilder.buildDefault().compare(a, b);

assert diff.hasChanges();
assert diff.childCount() == 1;
assert diff.getChild('prop1').getState() == DiffNode.State.CHANGED;
Answer from SQiShER on Stack Overflow
Top answer
1 of 8
56

Might be a little late, but I was in the same situation like you and ended up creating my own library for exactly your use-case. Since I was forced to come up with a solution myself, I decided to release it on Github, to spare others the hard work. You can find it here: https://github.com/SQiShER/java-object-diff

--- Edit ---

Here is a little usage example based on the OPs code:

SomeClass a = new SomeClass();
SomeClass b = new SomeClass();

a.setProp1("A");
a.setProp2("X");

b.setProp1("B");
b.setProp2("X");

DiffNode diff = ObjectDifferBuilder.buildDefault().compare(a, b);

assert diff.hasChanges();
assert diff.childCount() == 1;
assert diff.getChild('prop1').getState() == DiffNode.State.CHANGED;
2 of 8
54

http://javers.org is library that does exacly what you need: has methods like compare(Object leftGraph, Object rightGraph) returning the Diff object. Diff contains a list of changes (ReferenceChange, ValueChange, PropertyChange) e.g.

given:
DummyUser user =  dummyUser("id").withSex(FEMALE).build();
DummyUser user2 = dummyUser("id").withSex(MALE).build();
Javers javers = JaversTestBuilder.newInstance()

when:
Diff diff = javers.compare(user, user2)

then:
diff.changes.size() == 1
ValueChange change = diff.changes[0]
change.leftValue == FEMALE
change.rightValue == MALE

It can handle cycles in graphs.

In addition you can get Snapshot of any graph object. Javers has JSON serializers and deserializers to snapshot, and changes so you can easily save them in database. With this library you can easily implement a module for auditing.

🌐
Baeldung
baeldung.com › home › java › core java › comparing objects in java
Comparing Objects in Java | Baeldung
September 9, 2026 - However, that’s deprecated since Java 7, when Objects#equals appeared · Now let’s compare object order with the ObjectUtils#compare method. It’s a generic method that takes two Comparable arguments of that generic type and returns an Integer.
Discussions

Differences between 2 objects in java - Stack Overflow
I want to write a java program which has to find the differences between the two objects which is of different instances. I have implemented it using equals() and comparator. But here I want to find differences and have to show that in logging format. ... public class A implements Comparator{ private int id1, id2; /* setters and getters ... More on stackoverflow.com
🌐 stackoverflow.com
How to compare two Java objects?
By convention, each Java class has an equals method that is inherited from the base Object class. The actual implementation depends on the use case. In your example, you could check that the two objects have the same values for number, color and ball. More on reddit.com
🌐 r/javahelp
8
1
July 12, 2017
How does Java "==" operator check equality between objects? Trying to understand how Object.equals() works
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
20
1
January 8, 2023
Fastest way to compare property values in two variables?
A loop construct is generally faster than piping. $found = ForEach($v in $var1){ if($v.Property1 -eq $var2.Property2){ $v } } Depending on what your collection is, it might support Where(). You will have to test each to see what is faster: $found = $var1.Where({$_.Property1 -eq $var2.Property2}) Also, $matches is an automatic variable, you should avoid using it where it isn't provided for you. Your naming is not useful, as there is $var1 for an array, but $var2 for a single object you are comparing (what I have assumed from your code anyway). I suspect that you are actually wanting to loop through both arrays comparing each object. Maybe explain your intentions a bit clearer. More on reddit.com
🌐 r/PowerShell
25
6
September 24, 2023
🌐
Baeldung
baeldung.com › home › java › using the apache commons lang 3 for comparing objects in java
Using the Apache Commons Lang 3 for Comparing Objects in Java | Baeldung
January 8, 2024 - The resulting DiffResult provides a getDiffs() method for obtaining the differences found as a list of Diff objects. Diff class also offers practical methods for obtaining the compared fields. In this example, persons under comparison had a different first name, last name, city, and postal code.
🌐
Readthedocs
java-object-diff.readthedocs.io
java-object-diff Documentation
Node root = ObjectDifferBuilder.buildDefault().compare(workingObject, baseObject); This generates a tree structure of the given object type and lets you traverse its nodes via visitors. Each node represents one property (or collection item) of the underlying object and tells you exactly if and how the value differs from the base version.
🌐
Netlify
mallim.netlify.app › java-tips-how-to-compare-the-difference-for-two-given-java-objects
Java Tips: How to compare the difference for two given Java objects? | Mallim's Site
September 24, 2020 - Homepage: http://sqisher.github.io/java-object-diff/ Example 1 : https://morioh.com/p/c98c7721a9ed · Example 2 (Chinese) : https://blog.csdn.net/FENGQIYUNRAN/article/details/86683119 · Take note it might have problem with collections · Homepage: https://github.com/jdereg/java-util · The class we will be looking at is GraphComparator · Example 1 : https://turreta.com/2017/07/14/find-out-the-differences-between-two-objects-in-java/ Example 2 : https://advancedweb.hu/working-with-structured-data-in-java/
🌐
Quora
quora.com › Is-there-a-JAVA-API-class-framework-which-can-compare-two-objects-and-give-the-differences-between-them
Is there a JAVA API class (framework) which can compare two objects and give the differences between them? - Quora
Answer (1 of 3): Faced similar issue in one of the project I was working on. Technology stack consisted of Hibernate. There was need to provide audit feature on some of the domain objects and to show diff between consecutive version of the audit records. The solution used was Envers framework(Hib...
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-compare-two-objects
Java Program to Compare Two Objects - GeeksforGeeks
July 23, 2025 - // Java Program to Compare Two Objects // Importing java input/output libraries import java.io.*; // Class 1 class Pet { // Attributes of objects of class String name; int age; String breed; // Constructor Pet(String name, int age, String breed) { this.name = name; this.age = age; this.breed = breed; } // Overriding using hashCode() method @Override public int hashCode() { /* overriding hashCode() method to check the length of the names */ return this.name.length() % 10; } // Boolean function to check @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null |
Find elsewhere
🌐
Apache Commons
commons.apache.org › proper › commons-lang › javadocs › api-3.9 › org › apache › commons › lang3 › builder › DiffResult.html
DiffResult (Apache Commons Lang 3.9 API)
Use a DiffBuilder to build a DiffResult comparing two objects. ... Returns an unmodifiable list of Diffs. The list may be empty if there were no differences between the objects. ... Returns the number of differences between the two objects. ... Returns the style used by the toString() method.
🌐
Google Patents
patents.google.com › patent › US7814073B2 › en
US7814073B2 - Utility for identifying differences between two Java objects - Google Patents
In 146 , if one of the two objects is null, then “ONE_IS_NULL” is returned. If Object “a” and Object “b” are different classes, then “DIFFERENT_CLASSES” is returned in 148 . bracket 150 one of the JAVA equality methods is run on Object “a” and Object “b.” · 152 if “a” is an instance of a list, then the results of a call to the compareLists function is returned.
🌐
Medium
medium.com › @dr4wone › equals-vs-compareto-in-java-understanding-the-differences-fce0a0d4b292
Equals vs. compareTo in Java: Understanding the Differences | by Daniel Baumann | Medium
April 9, 2023 - In this example, we use the static method Integer.compare to compare the ages of two Person objects. This method returns a negative integer if the age of the current object is less than the age of the other object, zero if they are equal, and a positive integer if the age of the current object is greater than the age of the other object.
🌐
TutorialsPoint
tutorialspoint.com › java-program-to-compare-two-objects
Java Program to Compare Two Objects
July 31, 2024 - Two similar objects, returns same hash value if both objects are equal as per equals() method otherwise returns different hash value. In the following example, we are using both hashCode() and equals() methods to compare two objects in Java. ...
🌐
Msgprogramator
msgprogramator.sk › home › java › how to compare java objects correctly
Java Objects: How to Compare Them Correctly - msgprogramator.sk
July 7, 2025 - If we compare an object with its primitive type, either using the == operator or the equals method, it is equivalent, and if the values are the same, the result is a boolean true. The identity of a variable (also called reference equality) is defined by the reference it has. If two variables have the same reference, they are identical. This is controlled by the == operator. It is important to remember that the == operator in Java is used to compare the references of two objects, not their contents...
🌐
Javaprogramto
javaprogramto.com › 2020 › 08 › how-to-compare-two-objects-in-java-8.html
How To Compare Two Objects In Java 8 For Equality
August 9, 2020 - This program compiles and executes successfully. ... 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.
Top answer
1 of 5
2

To implement Comparator<A> you need a method public int compare(A o1, A o2). This is an example of such an implementation:

@Override
public int compare(A o1, A o2) {
    if (o1 == o2) {
        return 0;
    } else if (o1 == null) {
        return -1;
    } else if (o2 == null) {
        return 1;
    }
    if (o1.getId1() != o2.getId1()) {
        return o1.getId1() - o2.getId1();
    } else {
        return o1.getId2() - o2.getId2();
    }
}

Then you can use it like this:

    if (obj1.compare(obj1, obj2) == 0) {
        System.out.println("EQUALS");
    } else {
        System.out.println("NOT EQUALS");
    }

It is probably more common to make another class implement the Comparator<A>, instead of putting this in A itself.

2 of 5
1

You can use java Reflection to compare two same type beans those have getter for all comparing properties.

public static void compareBeans(Object bean1, Object bean2, String... propertyNames)
          throws IntrospectionException,
          IllegalAccessException, InvocationTargetException {
        Set<String> names = new HashSet<String>(Arrays
            .asList(propertyNames));
        BeanInfo beanInfo = Introspector.getBeanInfo(bean1
            .getClass());
        for (PropertyDescriptor prop : beanInfo
            .getPropertyDescriptors()) {
          if (names.remove(prop.getName())) {
            Method getter = prop.getReadMethod();
            Object value1 = getter.invoke(bean1);
            Object value2 = getter.invoke(bean2);
            if (value1 == value2
                || (value1 != null && value1.equals(value2))) {
              continue;
            }

            System.out.println("Property = "+prop.getName() +" Value of been1 ="+value1 +" : Value of bean2 ="+value2);
          }
        }
      }

Usage:

If i compare two beans of Student class which has two properties name and age like

BeanComparator.compareBeans(new Student("Amita", 21), new Student("Amit", 23) , props);

Output:

Property = age Value of been1 =21 : Value of bean2 =23
Property = name Value of been1 =Amita : Value of bean2 =Amit
🌐
Reddit
reddit.com › r/javahelp › how to compare two java objects?
r/javahelp on Reddit: How to compare two Java objects?
July 12, 2017 -

Hi there, it's my first time learning Java and I'd love some assistance with comparing two Java objects. Here is a KenoBall class:

public class KenoBall {

    private static int number;
    private static String colour;
    private static String ball;

    public KenoBall(int number, String colour) {
        this.number = number;
        this.colour = colour;
        this.ball = number + colour;
        System.out.print(number + colour + "\n");
    } 

    public boolean matches(KenoBall other) {
        if (What goes in here?) {
            System.out.println("Tru");
            return true;
        } else {
            System.out.println("False");
            return false;
        }
    } 

 }

And in my main method:

    public static void main(String[] args) {
        KenoBall k1 = new KenoBall(1, "R");
        KenoBall k2 = new KenoBall(1, "R");
        KenoBall k3 = new KenoBall(4, "B");
    
        k1.matches(k2);
    }

If anyone can point me in the right direction I'd really appreciate it! Basically I'm trying to see if k1 is equal to k2 (and it should).

Thank you!

🌐
Educative
educative.io › answers › what-is-objectscompare-in-java
What is Objects.compare() in Java?
The compare() method is a static method of the Objects class. This method takes in two objects and a Comparator that compares the input objects.
🌐
Wikibooks
en.wikibooks.org › wiki › Java_Programming › Comparing_Objects
Comparing Objects - Wikibooks, open books for an open world
To be able to compare two Java objects of the same class, the boolean equals(Object obj) method must be overridden and implemented by the class.
🌐
GitHub
github.com › SQiShER › java-object-diff
GitHub - SQiShER/java-object-diff: Library to diff and merge Java objects with ease · GitHub
java-object-diff is a simple, yet powerful library to find differences between Java objects. It takes two objects and generates a tree structure that represents any differences between the objects and their children.
Starred by 970 users
Forked by 176 users
Languages: Java 53.4% | Groovy 46.6%
🌐
GitConnected
levelup.gitconnected.com › comparing-objects-with-java-reflection-api-ae613c4f1532
Comparing Objects with Java Reflection | Level Up Coding
February 13, 2024 - Get information on Fields which are having different values after comparing two user objects using Java Reflection API.
🌐
Javatpoint
javatpoint.com › how-to-compare-two-objects-in-java
How to Compare Two Objects in Java - Javatpoint
How to Compare Two Objects in Java - How to Compare Two Objects in Java with java tutorial, features, history, variables, object, class, programs, operators, for-loop, oops concept, inheritance, array, string, map, math, methods, examples etc.