SoFunction
Updated on 2025-03-06

Java uses Collections tool class to sort List collections

This article mainly introduces Java to sort List collections using Collections tool class. The example code is introduced in this article in detail, which has certain reference value for everyone's learning or work. Friends who need it can refer to it.

1. Explanation

Use the sort method of the Collections tool class to sort list

Create a new comparator

2. Code

Sort by:

import ;
import ;
import ;
import ;

public class Test {

  public static void main(String[] args) {

    List<Student> list = new ArrayList<Student>();

    //Create 3 student objects, ages 20, 19, 21, and put them in the List in turn.    Student s1 = new Student();
    (20);
    Student s2 = new Student();
    (19);
    Student s3 = new Student();
    (21);
    (s1);
    (s2);
    (s3);

    ("Before sorting:"+list);

    (list, new Comparator<Student>(){

      /*
        * int compare(Student o1, Student o2) Returns an integer of the basic type,
        * Return negative number: o1 is less than o2,
        * Return to 0 means: o1 and o2 are equal,
        * Return positive number to indicate: o1 is greater than o2.
        */
      public int compare(Student o1, Student o2) {

        //Arrange ascending order according to the age of the students        if(() > ()){
          return 1;
        }
        if(() == ()){
          return 0;
        }
        return -1;
      }
    }); 
    ("After sorting:"+list);
  }
}

Student class:

class Student{
  private int age;
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
     = age;
  }
  @Override
  public String toString() {
    return getAge()+"";
  }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.