How to compare objects by multiple fields

后端 未结 22 2591
暖寄归人
暖寄归人 2020-11-22 00:43

Assume you have some objects which have several fields they can be compared by:

public class Person {

    private String firstName;
    private String lastN         


        
22条回答
  •  后悔当初
    2020-11-22 01:16

    Another option you can always consider is Apache Commons. It provides a lot of options.

    import org.apache.commons.lang3.builder.CompareToBuilder;
    

    Ex:

    public int compare(Person a, Person b){
    
       return new CompareToBuilder()
         .append(a.getName(), b.getName())
         .append(a.getAddress(), b.getAddress())
         .toComparison();
    }
    

提交回复
热议问题