Java, Software Development

Find Out the Differences between Two Objects in Java

This post demonstrates how to identify and list the differences between two objects using a set of classes and interfaces from Apache Commons Lang.

Classes, Intefaces, and pom.xml

The classes and interfaces to be used for this post are as follow:

  • org.apache.commons.lang3.builder.Diff
  • org.apache.commons.lang3.builder.DiffResult
  • org.apache.commons.lang3.builder.DiffBuilder
  • org.apache.commons.lang3.builder.Diffable
  • org.apache.commons.lang3.builder.ToStringStyle

We are using commons-lang3 version 3.6. We also use Java 8.

Scenario

We have two blog posts for our use case, and we need to list the differences between them. The list must show the affected field and the old-new (from post 1 to post 2) values.

Blog Post 1

For the first blog post, we have the following data.

  1. Title = First Post
  2. Content = This is my first post
  3. Except = My Blog Post

Blog Post 2

For the second blog post, we have the following data.

  1. Title = Second Post
  2. Content = This is my second post
  3. My Blog Post

The only difference between them is their titles and contents. Let’s list out the difference using some Java codes.

Java Codes

BlogPost class

It is a Java Bean that represents a blog post. Two things worth highlighting in these codes.

  1. The class implements the Diffable interface
  2. The class overrides the diff method
    • This is where the magic happens

DiffableDemo class

This is the main class – the entry point.

This outputs:

 

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like