How to compare objects by multiple fields

后端 未结 22 2598
暖寄归人
暖寄归人 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:34

    Starting from Steve's answer the ternary operator can be used:

    public int compareTo(Person other) {
        int f = firstName.compareTo(other.firstName);
        int l = lastName.compareTo(other.lastName);
        return f != 0 ? f : l != 0 ? l : Integer.compare(age, other.age);
    }
    

提交回复
热议问题