Java对象数组排序的三种方法->comparable,comparator,lambda表达式
以Employee为例,实现对象数组Employee[] employees的排序
1.类实现comparable
一个对象数组若要使用Arrays.sort(Object[] objects)方法来排序,那么该对象类需要实现comparable接口
public class Employee implements Comparable<Employee>{ private String name; private double salary; public Employee(){ name="Employee"; salary=0; } public Employee(String name,double salary){ this.name=name; this.salary=salary; } ...省略代码... public double getSalary(){ return salary; } public void setSalary(double salary){ this.salary=salary; } @Override public int compareTo(Employee o){ //return Double.compare(salary,o.salary); return Double.compare(this.getSalary(),o.getSalary()); } }
//1.Employee实现Comparable接口 Arrays.sort(employees);
2.往Arrays.sort()方法中传入Comparator对象来规定排序规则
class EmployeeComparator implements Comparator<Employee>{ @Override public int compare(Employee o1,Employee o2){ return Double.compare(o1.getSalary(),o2.getSalary()); } }
//2.使用Comparator比较器 Comparator comparator=new EmployeeComparator();
3.往Arrays.sort()方法传入lambda表达式
//3.使用Lambada表达式 Arrays.sort(employees,(o1,o2)->{ if(o1.getSalary()>o2.getSalary())return 1; else return -1; });