【问题标题】:ArrayList sorting on the basis of object property [duplicate]基于对象属性的ArrayList排序[重复]
【发布时间】:2014-03-06 18:00:52
【问题描述】:

以下是 Employee bean 类。

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

    public Employee()
    {

    }

    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;
    }
}

我还有其他 EmployeeTest 类,在其中我创建了 Employee 类的对象并存储在 ArrayList 中。

import java.util.ArrayList;

public class EmployeeTest {
    public static void main(String[] args) 
    {
        ArrayList<Employee> empList = new ArrayList<Employee>();
        Employee emp1 = new Employee();
        emp1.setAge(15);
        emp1.setName("Employee1");
        Employee emp2 = new Employee();
        emp2.setAge(10);
        emp2.setName("Employee1");
        empList.add(emp1);
        empList.add(emp2);
        for(Employee emp : empList)
        {
            System.out.println("employee name : " + emp.getName());
            System.out.println("employee age : " + emp.getAge());
        }
    }
}

现在我有一个问题是我想根据 Employee 类年龄属性对 ArrayList 进行排序。所以请解释我该如何排序。

【问题讨论】:

    标签: java sorting collections


    【解决方案1】:

    您可以将Collections.sort 方法与自定义Comparator 一起使用:

     import java.util.Collections;
     import java.util.Comparator;
    
     [...]
    
     Collections.sort(empList, new Comparator<Employee>() {
                    @Override public int compare(Employee x, Employee y) {
                       return Integer.compare(x.getAge(), y.getAge());
                    }
                });
    

    我用匿名Comparator类,你也可以写一个普通的Comparator类,见Sri Harsha Chilakapati回答。

    【讨论】:

    • 或者干脆做return Integer.compare(x.getAge(), y.getAge());
    • @ZouZou,谢谢!那肯定更好。
    【解决方案2】:

    这是一个简单的排序算法。我们存储最低年龄的下标值,以便我们可以交换它。​​

    for (int i = 0; i < empList.size(); i++)
            {
                int smallest = i;
                for (int j = i; j < numbers.length; j++)
                {
                    if (empList.get(j).getAge() < emplist.get(smallest).getAge())
                        smallest = j;
                }
    
                int temp = empList.get(i).getAge();
    
                empList.set(i, empList.get(smallest))
                empList.set(smallest, temp);
            }
    

    【讨论】:

      【解决方案3】:

      实现Comparable接口

      class Employee implements Comparable<Employee> {   
      

      像这样在Employee类中添加实现方法compareTo

       @Override
       public int compareTo(Employee other) {
           return this.age - other.age;
       }
      

      然后你可以像这里一样对你的列表进行排序:

      Collections.sort(empList)
      

      【讨论】:

        【解决方案4】:

        按照其他答案中的建议,让类实现 Comparable 接口是一种选择。

        但总的来说,我建议实现Comparable 接口,只要该类没有毫无疑问的自然顺序。对于Employee,肯定有NO 自然排序

        假设您想根据员工的年龄对员工进行排序。一次是升序,一次是降序。你怎么能做到这一点?现在想象一下,您想按他们的年龄对他们进行一次排序,一次按字母顺序,按他们的名字排序。如果不实现Comparator,您将无法做到这一点。这就是我在这里推荐的:

        你可以创建一个类似的方法

        private static Comparator<Employee> byAge()
        {
            return new Comparator<Employee>()
            {
                @Override
                public int compare(Employee o1, Employee o2)
                {
                    return o1.getAge() - o2.getAge();
                }
            };        
        }
        

        那么你可以简单地调用

        Collections.sort(empList, byAge());
        

        如果要倒序排列,可以调用

        Collections.sort(empList, Collections.reverseOrder(byAge()));
        

        如果要按名称对它们进行排序,可以创建一个方法

        private static Comparator<Employee> byName()
        {
            return new Comparator<Employee>()
            {
                @Override
                public int compare(Employee o1, Employee o2)
                {
                    return o1.getName().compareTo(o2.getName());
                }
            };        
        }
        

        并用

        对它们进行排序
            Collections.sort(empList, byName());
        

        这比实现Comparable 更加通用。

        【讨论】:

        • 很好的答案!不仅说明要做什么,还说明为什么要这样做。
        • @Marco13 或 Nigel 我想确认如果我使用 HashSet 而不是 ArrayList 会使用相同的方式吗?我知道这是一个简单的问题,但我们将不胜感激。
        • HashSet 无法排序。可以对 TreeSet 进行排序,但由于适用于那里的约束(即,根据排序标准,元素必须是唯一的),这里几乎不能使用。
        • 请查看这样做是否正确。 TreeSet empSet = new TreeSet(new Comparator() { @Override public int compare(Employee o1, Employee o2) { return o1.getAge() - o2.getAge(); } }); empSet.add(emp1); empSet.add(emp2); empSet.add(emp3); for(Employee emp : empSet) { System.out.println("员工姓名:" + emp.getName()); System.out.println("员工年龄:" + emp.getAge()); }
        • 您可以以这种方式将元素放入 TreeSet。当你这样做时,大致意味着可能没有两个年龄相同的员工! (这可能会导致进一步的问题,但这是基本思想)。另请参阅docs.oracle.com/javase/7/docs/api/java/util/Comparator.html BTW 上“consistent with equals”的比较器定义:cmets 不是发布代码的正确位置。
        【解决方案5】:

        你需要写一个比较器。

        class EmployeeAgeComparator implements Comparator<Employee>
        {
            @Override
            public int compare(Employee e1, Employee e2)
            {
                if (e1.getAge() > e2.getAge())
                {
                    return -1;
                } 
                else if (e1.getAge() < e2.getAge())
                {
                    return 1;
                }
                return 0;
            }
        }
        

        然后像这样使用Collections.sort方法。

        Collections.sort(empList, new EmployeeAgeComparator());
        

        希望这会有所帮助。

        【讨论】:

          【解决方案6】:

          我认为您可能希望对不同的属性进行排序,因此在这种情况下,您应该创建适当的比较器并将其与适当的排序方法(也需要该方法)一起使用。

          【讨论】:

          【解决方案7】:

          你的类必须实现 Comparable 接口并实现compareTo 方法。然后就可以使用Arrays.sort(yourArray)进行排序了。

          【讨论】:

            猜你喜欢
            • 2011-05-03
            • 2013-03-13
            • 2017-12-11
            • 2017-09-06
            • 2013-05-21
            • 2013-06-14
            • 2020-01-12
            • 1970-01-01
            • 2015-01-23
            相关资源
            最近更新 更多