I am trying to compare two objects of same class and the goal is to compare them as well as identify which fields didn't match.
Example of my domain class
@Builder(toBuilder=true)
class Employee {
String name;
int age;
boolean fullTimeEmployee;
}
Two objects
Employee emp1 = Employee.builder().name("john").age(25).fullTime(false).build();
Employee emp2 = Employee.builder().name("Doe").age(25).fullTime(true).build();
Comparing both objects
int result = Comparator.comparing(Employee::getName, Comparator.nullsFirst(Comparator.naturalOrder()))
.thenComparing(Employee::getAge, Comparator.nullsFirst(Comparator.naturalOrder()))
.thenComparing(Employee::isFullTimeEmployee, Comparator.nullsFirst(Comparator.naturalOrder()))
.compare(emp1, emp2);
result will be 0
because name
& fullTime
fields are not matching with each other.
But I also want to produce a list of fields which didn't match.. like below
List<String> unmatchedFields = ["name","fulltimeEmployee"];
Can I do it in a nicer way, other than bunch of if() else
Internally the Sort method does call Compare method of the classes it is sorting. To compare two elements, it asks “Which is greater?” Compare method returns -1, 0, or 1 to say if it is less than, equal, or greater to the other. It uses this result to then determine if they should be swapped for their sort.
Using Comparator with an anonymous inner class An anonymous inner class, in this case, is any class that implements Comparator . Using it means we are not bound to instantiating a named class implementing an interface; instead, we implement the compareTo() method inside the anonymous inner class.
'CompareTo' Method The method 'compareTo' of the Comparable interface is used to compare the current object to the given object.
The equals Method obj is the object to be tested for equality. The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false. Overriding equals( ) is unnecessary, and most simple comparators will not do so.
Check out DiffBuilder. It can report which items are different.
DiffResult<Employee> diff = new DiffBuilder(emp1, emp2, ToStringStyle.SHORT_PREFIX_STYLE)
.append("name", emp1.getName(), emp2.getName())
.append("age", emp1.getAge(), emp2.getAge())
.append("fulltime", emp1.getFulltime(), emp2.getFulltime())
.build();
DiffResult
has, among other things, a getDiffs()
method that you can loop over to find what differs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With