1. Overview

Comparing objects is one of the core concepts in Java, as well as in many other programming languages. It’s an essential concept when dealing with sorting, searching, and filtering data, which plays a crucial role in various aspects of programming.

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.

2. About Apache Commons Lang 3

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. The resulting differences are represented with the DiffResult class.

There is also an alternative to the DiffBuilderReflectionDiffBuilder – which serves the same purpose, but it’s based on reflection, while DiffBuilder is not.

3. Maven Dependencies

To use Apache Commons Lang 3, we first need to add the Maven dependency:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version>
</dependency>

4. Model

To demonstrate comparing two objects and obtaining their differences, we will use a Person class, along with PhoneNumber and Address classes:

public class Person {
    private String firstName;
    private String lastName;
    private int age;
    private List<PhoneNumber> phoneNumbers;
    private Address address;

    // standard constructors, getters and setters
}
public class PhoneNumber {
    private String type;
    private String number;

    // standard constructors, getters and setters
}
public class Address {
    private String streetAddress;
    private String city;
    private String postalCode;

    // standard constructors, getters and setters
}

5. Comparing Objects Using the DiffBuilder Class

Let’s demonstrate how to compare Person objects by using the DiffBuilder class. We’ll first start by defining a PersonDiffBuilder class with a compare() method:

public static DiffResult compare(Person first, Person second) {
    DiffBuilder diffBuilder = new DiffBuilder(first, second, ToStringStyle.DEFAULT_STYLE)
      .append("person", first.getFirstName(), second.getFirstName())
      .append("lastName", first.getLastName(), second.getLastName())
      .append("streetAddress", first.getAddress().getStreetAddress(), 
        second.getAddress().getStreetAddress())
      .append("city", first.getAddress().getCity(), second.getAddress().getCity())
      .append("postalCode", first.getAddress().getPostalCode(), 
        second.getAddress().getPostalCode())
      .append("age", first.getAge(), second.getAge());

    for (int i = 0; i < first.getPhoneNumbers().size(); i++) {
        diffBuilder.append("phoneNumbers[" + i + "].number", 
          first.getPhoneNumbers().get(i).getNumber(), 
          second.getPhoneNumbers().get(i).getNumber());
    }
    return diffBuilder.build();
}

Here, we use the DiffBuilder to implement the compare() method. When generating the DiffBuilder using the append() methods, we can control exactly which fields will be used in the comparison.

For demonstration purposes, when comparing the nested PhoneNumber objects, we omit comparing the type field, so two PhoneNumber objects with the same number and a different type field will be considered equal.

Optionally, we could make the Person class implement the Diffable interface and then use the DiffBuilder similarly to implement the diff() method.

Let’s see how we can put the PersonDiffBuilder class into practice and compare two Person objects:

@Test
void givenTwoPeopleDifferent_whenComparingWithDiffBuilder_thenDifferencesFound() {
    List<PhoneNumber> phoneNumbers1 = new ArrayList<>();
    phoneNumbers1.add(new PhoneNumber("home", "123-456-7890"));
    phoneNumbers1.add(new PhoneNumber("work", "987-654-3210"));

    List<PhoneNumber> phoneNumbers2 = new ArrayList<>();
    phoneNumbers2.add(new PhoneNumber("mobile1", "123-456-7890"));
    phoneNumbers2.add(new PhoneNumber("mobile2", "987-654-3210"));

    Address address1 = new Address("123 Main St", "London", "12345");
    Address address2 = new Address("123 Main St", "Paris", "54321");

    Person person1 = new Person("John", "Doe", 30, phoneNumbers1, address1);
    Person person2 = new Person("Jane", "Smith", 28, phoneNumbers2, address2);

    DiffResult<Person> diff = PersonDiffBuilder.compare(person1, person2);
    for (Diff<?> d : diff.getDiffs()) {
        System.out.println(d.getFieldName() + ": " + d.getLeft() + " != " + d.getRight());
    }

    assertFalse(diff.getDiffs().isEmpty());
}

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. The phone numbers have different types but equal numbers.

If we take a look at the System.out.println() output, we can see that all the differences have been found:

person: John != Jane
lastName: Doe != Smith
city: London != Paris
postalCode: 12345 != 54321
age: 30 != 28

6. Comparing Objects Using the ReflectionDiffBuilder Class

Let’s demonstrate how to compare Person objects by using the ReflectionDiffBuilder class. We’ll first start by defining a PersonReflectionDiffBuilder class with a compare() method:

public static DiffResult compare(Person first, Person second) {
    return new ReflectionDiffBuilder<>(first, second, ToStringStyle.SHORT_PREFIX_STYLE).build();
}

Here, we use the ReflectionDiffBuilder to implement the compare() method. There is no need to append individual fields for comparison, as all the non-static and non-transient fields are discovered using reflection.

In this example, the discovered fields would be firstName, lastName, age, phoneNumbers, and address. Internally, the ReflectionDiffBuilder uses the DiffBuilder, and it’s built using the discovered fields.

Suppose we want to exclude a specific discovered field from the comparison. In that case, we can use the @DiffExclude annotation to mark the fields we wish to exclude from the ReflectionDiffBuilder‘s use.

Since our Person class has a complex structure with nested objects, to ensure that ReflectionDiffBuilder correctly identifies the differences, we have to implement equals() and hashCode() methods.

For demonstration purposes, we will mark the address field from the Person class with the @DiffExclude annotation:

public class Person {
    private String firstName;
    private String lastName;
    private int age;
    private List<PhoneNumber> phoneNumbers;
    @DiffExclude
    private Address address;

    // standard constructors, getters and setters
}

We’ll also omit using the type field in the equals() and hashCode() methods for the PhoneNumber class:

@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }
    if (o == null || getClass() != o.getClass()) {
        return false;
    }
    PhoneNumber that = (PhoneNumber) o;
    return Objects.equals(number, that.number);
}

@Override
public int hashCode() {
    return Objects.hash(number);
}

Let’s see how we can use the PersonReflectionDiffBuilder class for comparing two Person objects:

@Test
void givenTwoPeopleDifferent_whenComparingWithReflectionDiffBuilder_thenDifferencesFound() {
    List<PhoneNumber> phoneNumbers1 = new ArrayList<>();
    phoneNumbers1.add(new PhoneNumber("home", "123-456-7890"));
    phoneNumbers1.add(new PhoneNumber("work", "987-654-3210"));

    List<PhoneNumber> phoneNumbers2 = new ArrayList<>();
    phoneNumbers2.add(new PhoneNumber("mobile1", "123-456-7890"));
    phoneNumbers2.add(new PhoneNumber("mobile2", "987-654-3210"));

    Address address1 = new Address("123 Main St", "London", "12345");
    Address address2 = new Address("123 Main St", "Paris", "54321");

    Person person1 = new Person("John", "Doe", 30, phoneNumbers1, address1);
    Person person2 = new Person("Jane", "Smith", 28, phoneNumbers2, address2);

    DiffResult<Person> diff = PersonReflectionDiffBuilder.compare(person1, person2);
    for (Diff<?> d : diff.getDiffs()) {
        System.out.println(d.getFieldName() + ": " + d.getLeft() + " != " + d.getRight());
    }

    assertFalse(diff.getDiffs().isEmpty());
}

In this example, persons under comparison had different first names, last names, and addresses. The phone numbers have different types but equal numbers. However, we put the @DiffExclude annotation on the address field to exclude it from the comparison.

If we take a look at the System.out.println() output, we can see that all the differences have been found:

firstName: John != Jane
lastName: Doe != Smith
age: 30 != 28

7. Conclusion

In this article, we demonstrated how to compare Java objects using the DiffBuilder and the ReflectionDiffBuilder from the Apache Commons Lang 3 library.

Both classes are easy to use and offer a convenient way to compare objects, although each has advantages and disadvantages.

We have seen through the examples in this article that DiffBuilder offers more customization and is more explicit. Still, it might result in increased complexity for more complex objects.

ReflectionDiffBuilder offers more simplicity but has limited customization options and might introduce performance overhead since it uses reflection.

Code from this article can be found over on GitHub.

Course – LS (cat=Java)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.