所謂集合排序是指對集合內的元素進行排序。
集合工具類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;}@Overridepublic String toString() {return "Student [id=" + id + ", name=" + name + "]";}@Overridepublic 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;}@Overridepublic 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>() {@Overridepublic int compare(Student o1, Student o2) {return o2.getId()-o1.getId();}});for(Student student:list){System.out.println(student);}}
}
?