According to your requirement you can do this as follow.

you can take two database rows to two objects. Eg: SampleObject

public class SampleObject {

private String name;
private int age;
private String email;   

public SampleObject(String name, int age, String email) {
    this.name = name;
    this.age = age;
    this.email = email;
}
.
.

I imagine your results will be an object too. Eg : ResultObject

public class ResultObject {

private String fieldName;
private String OldObjectValue;
private String NewObjectValue;
.
.

You can just define a compareField kind of method in SampleObject

public List<ResultObject> compareFields(SampleObject object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
    List<ResultObject> resultList = new ArrayList<ResultObject>();      
    Field[] fields = this.getClass().getDeclaredFields();

    for(Field field : fields){
        if(!field.get(this).equals(field.get(object))){
            ResultObject resultObject = new ResultObject();
            resultObject.setFieldName(field.getName());
            resultObject.setOldObjectValue(field.get(this).toString());
            resultObject.setNewObjectValue(field.get(object).toString());
            resultList.add(resultObject);
        }
    }
    return resultList;
}

Then you can make it work.

SampleObject object1 = new SampleObject("ABC", 29, "[email protected]");
    SampleObject object2 = new SampleObject("XYZ", 29, "[email protected]");

    List<ResultObject> resultList = object1.compareFields(object2);

Thanks

Answer from isurujay on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › core java › comparing objects in java
Comparing Objects in Java | Baeldung
October 10, 2025 - Let’s take the Ints helper class and see how its compare() method works: ... As usual, it returns an integer that may be negative, zero, or positive if the first argument is lesser, equal, or greater than the second, respectively.
Discussions

compare two objects
All these exceptions will need to be very solidly decided on and written out. You can't just say "some fields like this one may have different names", because the code won't be able to tell that this is "one of the some". What I'd do is map both of these arrays and run them through the same "equalizer" function, that takes into account all these rules and sets them all to the same variables. Then, since some don't matter for equality, you'll have to iterate over each key and check for equality manually. No === will recognize "oh, but "living_the_life" doesn't actually matter for this === so it's all good", you know? Or, in your equalizer function, you can also delete any keys that don't matter, and then you could check equality in a number of ways. A popular one is JSON.stringify(a) === JSON.stringify(b), which works most of the time but the order of the properties matters. Since you'd be running it through an equalizer, I think you can be certain of the order of the properties so that should be enough. More on reddit.com
🌐 r/learnjavascript
5
2
September 1, 2022
java - how to compare two objects and find the fields/properties changed? - Stack Overflow
I need to write some generic solution to find out what properties in two objects have changed and return the changed properties (not the value). class Student { public String name; public More on stackoverflow.com
🌐 stackoverflow.com
java - How to compare two objects and get the changed fields - Stack Overflow
In here im logging the changes that has been done to a particular Object record. So im comparing the old record and the updated record to log the updated fields as a String. Any idea how can I do t... More on stackoverflow.com
🌐 stackoverflow.com
Optimal way to compare two objects of the same type
If you have record the C# will automatically generate Equals method for you that will compare all properties. More on reddit.com
🌐 r/dotnet
24
6
February 22, 2024
🌐
CopyProgramming
copyprogramming.com › howto › compare-two-objects-field-by-field-and-show-the-difference
How to Compare Two Java Objects Field by Field: Complete Guide for 2026 - Compare two java objects field by field complete guide
November 22, 2025 - How do I compare two objects field by field without implementing equals()? Use reflection-based utilities like Apache Commons Lang's ReflectionDiffBuilder or the java-object-diff library, which automatically compare all fields without requiring equals() implementation.
🌐
GitConnected
levelup.gitconnected.com › comparing-objects-with-java-reflection-api-ae613c4f1532
Comparing Objects with Java Reflection API - Level Up Coding
February 13, 2024 - Get information on Fields which are having different values after comparing two user objects using Java Reflection API.
🌐
Salesforce
trailhead.salesforce.com › trailblazer-community › feed › 0D54V00007T4DMpSAN
Compare Fields in 2 different | Salesforce Trailblazer Community
February 25, 2019 - From 16:00 UTC on January 17, 2026, to 20:00 UTC on January 17, 2026, we will perform planned maintenance on the Trailhead, myTrailhead, and Trailblazer Community sites. During the maintenance, these sites will be unavailable, and users won't be able to access them.
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › microsoft.powershell.utility › compare-object
Compare-Object (Microsoft.PowerShell.Utility) - PowerShell | Microsoft Learn
The Compare-Object cmdlet compares two sets of objects. One set of objects is the reference, and the other set of objects is the difference. Compare-Object checks for available methods of comparing a whole object.
Find elsewhere
🌐
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 - Comparing objects in Java can be done manually by implementing the comparison logic or using libraries with object comparison abilities. Various libraries can be used for comparing objects in Java, such as JaVers or Apache Commons Lang 3, which we will cover in this article. Apache Commons Lang 3 represents the 3.0 version of the Apache Commons Lang library, which offers many functionalities. We will explore the DiffBuilder class to compare and obtain the differences between two objects of the same type.
🌐
Reddit
reddit.com › r/learnjavascript › compare two objects
r/learnjavascript on Reddit: compare two objects
September 1, 2022 -

I have two objects that I need to compare if they are equal. They will only contain JS primitives and JS Date objects.

object a
{
  first_name: "Fred",
  last_name: "Flintstone",
  modified_datetime: 2022-09-01Z00:00:00,
  age: 42,
  has_children: true,
  living_the_life: "maybe",
}
object b
{
  firstName: "Fred",
  lastName: "Flintstone",
  modified: 2022-09-01Z00:00:00,
  yearsAlive: 42,
  hasChildren: true,
  living_the_life: "i don't care about this field",
}

I would like to compare these two object. The field names are similar, but will not always follow a convention (ie make snake case = camel case). Some fields like age => yearsAlive have completely different names... other fields like living_the_life are completely ignored. My first inclination is just a Map() object to map fields from object a to object b. Run through the keys of that map checking for equality. It's plausible a field like age maybe be passed in as a number or string... I think using == makes sense ... but would prefer === and force those send data to send the appropriate data type. Is there a clever library or even lodash function that already has this functionality? Or just build it myself? In this case object a = object b.

Top answer
1 of 5
14

I think this is the method you searching for:

 private static List<String> difference(Student s1, Student s2) throws IllegalAccessException {
     List<String> changedProperties = new ArrayList<>();
     for (Field field : s1.getClass().getDeclaredFields()) {
        // You might want to set modifier to public first (if it is not public yet)
        field.setAccessible(true);
        Object value1 = field.get(s1);
        Object value2 = field.get(s2); 
        if (value1 != null && value2 != null) {
            System.out.println(field.getName() + "=" + value1);
            System.out.println(field.getName() + "=" + value2);
            if (!Objects.equals(value1, value2)) {
                changedProperties.add(field.getName());
            }
        }
    }
    return changedProperties;
 }
2 of 5
12

This is an enhancement of Dumbo's difference method, using recursion to check all nested complex fields.

    private static void difference(Object s1, Object s2, List<String> changedProperties, String parent) throws IllegalAccessException {
        for (Field field : s1.getClass().getDeclaredFields()) {
            if (parent == null) {
                parent = s1.getClass().getSimpleName();
            }
            field.setAccessible(true);
            Object value1 = field.get(s1);
            Object value2 = field.get(s2);
            if (value1 == null && value2 == null) {
                continue;
            }
            if (value1 == null || value2 == null) {
                changedProperties.add(parent + "." + field.getName());
            } else {
                if (isBaseType(value1.getClass())) {
                    if (!Objects.equals(value1, value2)) {
                        changedProperties.add(parent + "." + field.getName());
                    }
                } else {
                    difference(value1, value2, changedProperties, parent + "." + field.getName());
                }
            }
        }
    }

    private static final Set<Class> BASE_TYPES = new HashSet(Arrays.asList(
            String.class, Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class, Void.class));
    public static boolean isBaseType(Class clazz) {
        return BASE_TYPES.contains(clazz);
    }

Sample usage (assumes the referenced model objects have getters/setters):

    public static void main(String[] args) throws IllegalAccessException {
        Student s1 = new Student();
        s1.setName("Krishna");
        s1.setAge(30);
        Address address = new Address();
        s1.setAddress(address);
        s1.getAddress().setHno("2-2-22");
        s1.getAddress().setStreet("somewhere");
        s1.getAddress().setPin(123);

        Student s2 = new Student();
        s2.setName("Krishna");
        s2.setAge(20);
        address = new Address();
        s2.setAddress(address);
        s2.getAddress().setHno("1-1-11");
        s2.getAddress().setStreet("nowhere");
        s2.getAddress().setPin(123);
        List<String> changedProperties = new ArrayList<>();

        difference(s1, s2, changedProperties, null);
        System.out.println("changedProperties = " + changedProperties);
        // expected result
        // Student.age
        // Student.address.hno
        // Student.address.street
    }

Result:

changedProperties = [Student.address.hno, Student.address.street, Student.age]

Primitive adapting checking adapted from https://stackoverflow.com/a/711226/1527469

🌐
DEV Community
dev.to › digitaldrreamer › how-to-compare-diff-two-objects-2ocd
How to Compare (diff) two Objects - DEV Community
January 7, 2026 - API Updates: Determine which fields to send in PATCH requests · Audit Logging: Record specific changes made to data · Nested Objects: Deep comparison vs shallow comparison · Arrays: Order sensitivity and reference comparison ... PS: Here's a Github gist for a simple function to compare and get the difference between two objects:
🌐
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)
A DiffResult contains a collection of the differences between two Diffable objects. Typically these differences are displayed using toString() method, which returns a string describing the fields that differ between the objects. Use a DiffBuilder to build a DiffResult comparing two objects.
🌐
Reddit
reddit.com › r/dotnet › optimal way to compare two objects of the same type
r/dotnet on Reddit: Optimal way to compare two objects of the same type
February 22, 2024 -

To give some background, I need to compare a List of a certain Entity from my DB to a List of that same entity type from an External API. Both lists are going to be mapped to the same DTO Record so they will be identical. The DTO is linked by a common ExternalID, after having both matching DTOs, I need to check if any of the field values are different between two objects (Id and ExternalId don't need to be compared). Below is the DTO I will be doing the comparison on.

public record TestDto
{
	public Guid Id { get; set; }
	public int? ExternalId { get; set; }
	public string? Name { get; set; }
	public string? EventType { get; set; }
	public int? TicketQuantity { get; set; }
	public float? TotalTicketCost { get; set; }
	public int? ListingCount { get; set; }
	public int? ExternalCategoryId { get; set; }
	public string? ExternalCategoryName { get; set; }
}

I know multiple ways I can do this however they are far from optimal. I am looking for the most optimal way to go about it since I will need to do this for 5K+ records.

🌐
JSON Diff
jsondiff.com
JSON Diff - The semantic JSON compare tool
Validate, format, and compare two JSON documents. See the differences between the objects instead of just the new lines and mixed up properties. Created by Zack Grossbart.
Top answer
1 of 5
3

The “different member variables” is irrelevant. It’s an implementation detail. What you need is a set of rules which of two people comes first.

You could for example sort by family name, then given name, then date of birth, and if these are all three equal, take the name of the school, university or company (which will be different member variables) and compare them as strings. If that is equal, you might have student and employee ids, and the student ids might be unique, and the employee ids might be unique, but student and employee ids might be the same. So you could sort then students first ordered by id, followed by employees sorted by id, if you might sort by if first if student and employee ids are comparable.

(University or school and employer might be the same, because universities are also employers).

2 of 5
3

Comparing objects with different fields sounds like bad polymorphic design, whether it's Java or any other OOP language:

  • If your comparator needs to know the precise subtype of an object to do the comparison, you mess-up with the the open-closed principle, since for every new subclassing, you'd potentially need to modify the comparator to select the relevant fields.
  • If your comparator needs uses reflexion to find on its own the relevant fields to compare, you indirectly mess up with the principle of encapsulation, since you create a hidden requirement that information to be compared must be in some predetermined field.

If you want to sort People properly in a clean polymorphic design:

  • you need to rely either on a field, available for any kind of People, including Student, or
  • you may call some function/transformation that provides a unique value (e.g. a string) that allows to sort any People. People and Student may then just use a different transformation that will be passed to the comparator; Or
  • you only sort among homogeneous subtypes.
🌐
Experts Exchange
experts-exchange.com › questions › 29272723 › C-Compare-2-Objects.html
Solved: C# Compare 2 Objects | Experts Exchange
May 2, 2024 - Assuming you're comparing using ... is to use the JavaScriptSerializer or XmlSerializer to create a JSON or XML representation of the customer object, then SHA-1 hash it and save the hash into a separate field....
🌐
Medium
gbahdeyboh.medium.com › a-guide-to-object-based-comparison-in-javascript-e57d6f244f48
A Guide To Object Based Comparison In JavaScript | by Gbadebo Bello | Medium
June 15, 2019 - Everything in JavaScript can be represented as an object including its primitive data types. When we want to check for equality between two data types, we simply use comparison operators on this two data types.
🌐
SamanthaMing
samanthaming.com › tidbits › 33-how-to-compare-2-objects
How to Compare 2 Objects in JavaScript 🎉 | SamanthaMing.com
July 23, 2025 - const one = { fruit: '🥝', nutrients: { energy: '255kJ', minerals: { name: 'calcium', }, }, }; const two = { fruit: '🥝', nutrients: { energy: '255kJ', minerals: { name: 'calcium', }, }, }; // Using JavaScript JSON.stringify(one) === JSON.stringify(two); // true // Using Lodash _.isEqual(one, two); // true · Well that depends. For JSON.stringify(), the order matters. So if the key-value pair are ordered differently in the two objects but are the same, it will return false.