對List集合進行排序


轉自:https://www.cnblogs.com/wslook/p/9385871.html

一、說明

  • 使用Collections工具類的sort方法對list進行排序
  • 新建比較器Comparator

二、代碼

排序:

復制代碼
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、19、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);
    }
}
復制代碼

 

Student類:

復制代碼
class Student{

    private int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return getAge()+"";
    }
}
復制代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM