Recently I worked on a requirement where we needed to audit the change/difference in the entity resource so looked over the internet to get a utility that can return the difference between two java objects (or Map objects) like — updated, added, removed fields. Also, the difference should be serializable so that they can be persisted or transferred over the network.
I found Google’s Guava API which gives Maps.difference() utility function to get the difference between 2 input Map objects, but it has a basic limitation of not being serializable (eg. com.google.common.collect.MapDifferenceImpl, com.google.common.collect.ValueDifferenceImpl) and sometimes we avoid using guava API as it causes dependency issues.
So in order to add a serializable difference field(eg. MapDifference<String, Object>) in a Data Transfer Object(DTO), I defined a new Utility class which returns a serializable MapDifference object similar to one defined by Guava and uses very common open source Jackson JSON API for converting Java Object to a Map instance.
Let us look into the implementation details of the MapDifferenceUtils :
Where to use MapDifferenceUtils.difference() ?
Normally it can be used anywhere in the application however, one of the cases could be to use it in the Repository layer to return the MapDifference object for the update operation as below :
This handy MapDifferenceUtils can be used in various scenarios especially where we want to find what changed between the two java objects (not the primitives).