eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

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

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LS – NPI (cat=Java)
announcement - icon

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

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)