集合類List存放的數據,默認是按照放入時的順序存放的,好比依次放入A、B、C,則取得時候,則也是A、B、C的順序,實際場景中,有時咱們須要根據自定義的規則對List中的元素進行排序,該如何實現呢?看下面小例子:html
[html] view plain copyjava
![在CODE上查看代碼片](http://static.javashuo.com/static/loading.gif)
![派生到個人代碼片](http://static.javashuo.com/static/loading.gif)
- package test.tool.gui.dbtool.util;
-
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.List;
-
- public class Test {
-
- public static void main(String[] args) {
-
- List<Student> list = new ArrayList<Student>();
-
- //建立3個學生對象,年齡分別是20、1九、21,並將他們依次放入List中
- Student s1 = new Student();
- s1.setAge(20);
- Student s2 = new Student();
- s2.setAge(19);
- Student s3 = new Student();
- s3.setAge(21);
- list.add(s1);
- list.add(s2);
- list.add(s3);
-
- System.out.println("排序前:"+list);
-
- Collections.sort(list, new Comparator<Student>(){
-
- /*
- * int compare(Student o1, Student o2) 返回一個基本類型的整型,
- * 返回負數表示:o1 小於o2,
- * 返回0 表示:o1和o2相等,
- * 返回正數表示:o1大於o2。
- */
- public int compare(Student o1, Student o2) {
-
- //按照學生的年齡進行升序排列
- if(o1.getAge() > o2.getAge()){
- return 1;
- }
- if(o1.getAge() == o2.getAge()){
- return 0;
- }
- return -1;
- }
- });
- System.out.println("排序後:"+list);
- }
- }
- class Student{
-
- private int age;
-
- public int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
- @Override
- public String toString() {
- return getAge()+"";
- }
- }
執行結果:app
[html] view plain copyide
![在CODE上查看代碼片](http://static.javashuo.com/static/loading.gif)
![派生到個人代碼片](http://static.javashuo.com/static/loading.gif)
- 排序前:[20, 19, 21]
- 排序後:[19, 20, 21]
固然對象的屬性能夠多個,好比按年齡升序,按成績降序等 .ui