溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何在Java中使用Collections工具類排序List集合

發(fā)布時間:2021-03-23 16:01:20 來源:億速云 閱讀:312 作者:Leah 欄目:編程語言

如何在Java中使用Collections工具類排序List集合?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

一、說明

使用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>();

    //創(chuàng)建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()+"";
  }
}

看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI