创建bean实现 Comparator, Comparable 两个接口,重写compare和compareTo两个方法
public class Student implements Comparator<Student>, Comparable<Student> { private Integer id; private String name; public Student() { } public Student(Integer id, String name) { this.id = id; this.name = name; } @Override public int compare(Student o1, Student o2) { //返回负数,第一个参数排在前面 //返回正数,第二个参数排在前面 if (o1.getId() > o2.getId()) { return 1; } else if (o1.getId() < o2.getId()) { return -1; } else { return 0; } } @Override public int compareTo(Student o) { return (this.name).compareTo(o.name); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return Objects.equals(id, student.id) && Objects.equals(name, student.name); } @Override public int hashCode() { return Objects.hash(id, name); } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
使用
public static void main(String[] args) { Student student1 = new Student(1, "ddd"); Student student2 = new Student(2, "ccc"); Student student3 = new Student(3, "bbb"); Student student4 = new Student(4, "aaa"); Student[] arrStudents = {student3, student2, student1, student4}; Arrays.sort(arrStudents); for (Student arrStudent : arrStudents) { System.out.println(arrStudent); } }
结果:
Student{id=4, name='aaa'} Student{id=3, name='bbb'} Student{id=2, name='ccc'} Student{id=1, name='ddd'} Process finished with exit code 0