我如何在arrayList中对对象进行排序?

时间:2017-10-13 16:46:35

标签: java sorting arraylist

我试图在arrayList中对对象进行排序。可能像Node和Edge。 例如:我有这样的对象:

  

Object2 [B,C],Object1 [A,B],Object4 [E,F],Object3 [C,D],   Object5 [F,G],......

我的问题是如何将其分类为这样的组:

  

Object1 [A,B],Object2 [B,C],Object3 [C,D] = Group1 Object4 [E,F],   Object5 [F,G] = Group2 ......

我该怎么办?

1 个答案:

答案 0 :(得分:0)

使用可比较比较器,如下所示,您还可以访问https://www.journaldev.com/780/comparable-and-comparator-in-java-example了解详情。

    import java.util.Comparator;

    class Employee implements Comparable<Employee> {

        private int id;
        private String name;
        private int age;
        private long salary;

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        public int getAge() {
            return age;
        }

        public long getSalary() {
            return salary;
        }

        public Employee(int id, String name, int age, int salary) {
            this.id = id;
            this.name = name;
            this.age = age;
            this.salary = salary;
        }

        @Override
        public int compareTo(Employee emp) {
            //let's sort the employee based on id in ascending order
            //returns a negative integer, zero, or a positive integer as this employee id
            //is less than, equal to, or greater than the specified object.
            return (this.id - emp.id);
        }

        @Override
        //this is required to print the user friendly information about the Employee
        public String toString() {
            return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" +
                    this.salary + "]";
        }
}

Default Sorting of Employees list: [[id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000]]