2021年1月20日星期三

Comparator.comparing(...).thenComparing(...) find out which fields did not match

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

https://stackoverflow.com/questions/65816162/comparator-comparing-thencomparing-find-out-which-fields-did-not-match January 21, 2021 at 03:16AM

没有评论:

发表评论