基于对象属性的排序
以下是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 empList = new ArrayList(); 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类的age属性对ArrayList进行排序。 所以请解释我该如何排序。
让其实现Comparable
接口,如其他答案所示,是一种选择。
但总的来说,我建议不要实现Comparable
接口,只要该类没有毫无疑问的自然顺序 。 而对于Employee
,肯定没有 自然的顺序 。
想象一下,你想根据他们的年龄对员工进行排序。 一旦按升序排列,一次按降序排列。 你怎么能做到这一点? 现在想象一下你想按照他们的年龄对它们进行一次排序,并按字母顺序排列一次。 如果没有实现Comparator
,你就无法做到这一点。 这就是我在这里推荐的内容:
你可以创建一个类似的方法
private static Comparator byAge() { return new Comparator () { @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 byName() { return new Comparator () { @Override public int compare(Employee o1, Employee o2) { return o1.getName().compareTo(o2.getName()); } }; }
然后用它们排序
Collections.sort(empList, byName());
这比实现Comparable
更加通用。
您可以将Collections.sort方法与自定义Comparator一起使用 :
import java.util.Collections; import java.util.Comparator; [...] Collections.sort(empList, new Comparator() { @Override public int compare(Employee x, Employee y) { return Integer.compare(x.getAge(), y.getAge()); } });
我用过匿名的Comparator
类,你也可以写一个普通的Comparator
类,看看Sri Harsha Chilakapati的答案。
你需要写一个比较器。
class EmployeeAgeComparator implements Comparator { @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());
希望这可以帮助。
实现Comparable
接口
class Employee implements Comparable {
在Employee
类中添加实现方法compareTo
如下:
@Override public int compareTo(Employee other) { return this.age - other.age; }
然后你可以像这里一样排序你的列表:
Collections.sort(empList)
您的类必须实现Comparable接口并实现compareTo
方法。 然后你可以使用Arrays.sort(yourArray)
对它进行排序。
我想你可能想要对不同的属性进行排序,所以在这种情况下你应该创建适当的比较器并使用正确的排序方法(也需要它)。
这是一种简单的排序算法。 我们存储最低年龄的下标值,以便我们可以交换它。
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); }