How to compare objects by multiple fields

后端 未结 22 2593
暖寄归人
暖寄归人 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条回答
  •  梦毁少年i
    2020-11-22 01:34

    import com.google.common.collect.ComparisonChain;
    
    /**
     * @author radler
     * Class Description ...
     */
    public class Attribute implements Comparable {
    
        private String type;
        private String value;
    
        public String getType() { return type; }
        public void setType(String type) { this.type = type; }
    
        public String getValue() { return value; }
        public void setValue(String value) { this.value = value; }
    
        @Override
        public String toString() {
            return "Attribute [type=" + type + ", value=" + value + "]";
        }
    
        @Override
        public int compareTo(Attribute that) {
            return ComparisonChain.start()
                .compare(this.type, that.type)
                .compare(this.value, that.value)
                .result();
        }
    
    }
    

提交回复
热议问题