所谓集合排序是指对集合内的元素进行排序。
集合工具类Collections中提供了两种排序算法,分别是:
- Collections.sort(List list)
- Collections.sort(List list,Comparator c)
Collections.sort(List list)这种方式需要对象实现Comparable接口,并重写compareTo()方法。
import java.util.Collections;
import java.util.LinkedList;
public class Student implements Comparable<Student>{
private int id;
private String name;
public Student(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
@Override
public int compareTo(Student stu) {
return stu.id-this.id;//实现id倒序
}
public static void main(String[] args) {
Student stu = new Student(2,"张三");
Student stu2 = new Student(1,"李四");
Student stu3 = new Student(5,"王五");
LinkedList<Student> list = new LinkedList<Student>();
list.add(stu);
list.add(stu2);
list.add(stu3);
Collections.sort(list);
for(Student student:list){
System.out.println(student);
}
}
}
Collections.sort(List list,Comparator c)这种方式比较灵活,只需要提供比较器实例就可以了。
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
public class Student{
private int id;
private String name;
public Student(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
public static void main(String[] args) {
Student stu = new Student(2,"张三");
Student stu2 = new Student(1,"李四");
Student stu3 = new Student(5,"王五");
LinkedList<Student> list = new LinkedList<Student>();
list.add(stu);
list.add(stu2);
list.add(stu3);
Collections.sort(list,new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o2.getId()-o1.getId();
}
});
for(Student student:list){
System.out.println(student);
}
}
}