How to use Java comparator properly?

前端 未结 7 1627
孤街浪徒
孤街浪徒 2020-12-11 05:42

If I have the following class:

public class Employee {
    private int empId;
    private String name;
    private int age;

    public Employee(int empId, S         


        
相关标签:
7条回答
  • 2020-12-11 06:41

    Implement it

    public class Employee {
        private int empId;
        private String name;
        private int age;
        /**
         * @param empId
         * @param name
         * @param age
         */
        public Employee(int empId, String name, int age) {
            super();
            this.empId = empId;
            this.name  = name;
            this.age   = age;
        }
        /**
         * 
         */
        public Employee() {
            super();
            // TODO Auto-generated constructor stub
        }
    
    
        public int getEmpId() {
            return empId;
        }
        public void setEmpId(int empId) {
            this.empId = empId;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
    
        //Compare by name, age and then id
        public static Comparator<Employee> COMPARE_EMPLOYEE = new Comparator<Employee>() {
            public int compare(Employee one, Employee other) {
                //Compare Name
                if (one.getName().compareToIgnoreCase(other.getName()) == 0) {
                    //Compare age
                    if((one.getAge() - other.getAge()) == 0) {
                        // Now check with id is useless
                        // So directly return result of compare by id
                        return one.getEmpId() - other.getEmpId();
                    } else { //If age Not equal
                        return one.getAge() - other.getAge();
                    }
                } else { //If name not equal
                    return one.getName().compareToIgnoreCase(other.getName());
                }
            }
        };
    }
    

    Use :

    List<Employee> contacts = new ArrayList<Employee>();
    //Fill it.
    
    //Sort by address.
    Collections.sort(contacts, Employee.COMPARE_EMPLOYEE);
    

    Read Sorting an ArrayList of Contacts , this must help you and you will get more ideas and different different types of use of Comparator.

    0 讨论(0)
提交回复
热议问题