How to compare objects by multiple fields

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

    You can also have a look at Enum that implements Comparator.

    http://tobega.blogspot.com/2008/05/beautiful-enums.html

    e.g.

    Collections.sort(myChildren, Child.Order.ByAge.descending());
    
    0 讨论(0)
  • 2020-11-22 01:30

    Instead of comparison methods you may want to just define several types of "Comparator" subclasses inside the Person class. That way you can pass them into standard Collections sorting methods.

    0 讨论(0)
  • 2020-11-22 01:30

    If there are multiple ways a user might order person, you could also have multiple Comparators setup as constants somewhere. Most of the sort operations and sorted collections take a comparator as a parameter.

    0 讨论(0)
  • 2020-11-22 01:33
    //Following is the example in jdk 1.8
    package com;
    import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.List;
    
    class User {
        private String firstName;
        private String lastName;
        private Integer age;
    
        public Integer getAge() {
            return age;
        }
    
        public User setAge(Integer age) {
            this.age = age;
            return this;
        }
    
        public String getFirstName() {
            return firstName;
        }
    
        public User setFirstName(String firstName) {
            this.firstName = firstName;
            return this;
        }
    
        public String getLastName() {
            return lastName;
        }
    
        public User setLastName(String lastName) {
            this.lastName = lastName;
            return this;
        }
    
    }
    
    public class MultiFieldsComparision {
    
        public static void main(String[] args) {
            List<User> users = new ArrayList<User>();
    
            User u1 = new User().setFirstName("Pawan").setLastName("Singh").setAge(38);
            User u2 = new User().setFirstName("Pawan").setLastName("Payal").setAge(37);
            User u3 = new User().setFirstName("Anuj").setLastName("Kumar").setAge(60);
            User u4 = new User().setFirstName("Anuj").setLastName("Kumar").setAge(43);
            User u5 = new User().setFirstName("Pawan").setLastName("Chamoli").setAge(44);
            User u6 = new User().setFirstName("Pawan").setLastName("Singh").setAge(5);
    
            users.add(u1);
            users.add(u2);
            users.add(u3);
            users.add(u4);
            users.add(u5);
            users.add(u6);
    
            System.out.println("****** Before Sorting ******");
    
            users.forEach(user -> {
                System.out.println(user.getFirstName() + " , " + user.getLastName() + " , " + user.getAge());
            });
    
            System.out.println("****** Aftre Sorting ******");
    
            users.sort(
                    Comparator.comparing(User::getFirstName).thenComparing(User::getLastName).thenComparing(User::getAge));
    
            users.forEach(user -> {
                System.out.println(user.getFirstName() + " , " + user.getLastName() + " , " + user.getAge());
            });
    
        }
    
    }
    
    0 讨论(0)
  • 2020-11-22 01:34
    import com.google.common.collect.ComparisonChain;
    
    /**
     * @author radler
     * Class Description ...
     */
    public class Attribute implements Comparable<Attribute> {
    
        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();
        }
    
    }
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
提交回复
热议问题