如何在Java中使用Collections工具类排序List集合
更新:HHH   时间:2023-1-8


如何在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>();

    //创建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()+"";
  }
}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注天达云行业资讯频道,感谢您对天达云的支持。

返回编程语言教程...