What is the method to sort ArrayList in Java?

In Java, you can sort an ArrayList using the sort method of the Collections class. Sample code is shown below:

import java.util.ArrayList;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(5);
        list.add(2);
        list.add(8);
        list.add(1);
        
        // 对ArrayList进行排序
        Collections.sort(list);
        
        // 输出排序后的结果
        for (int num : list) {
            System.out.println(num);
        }
    }
}

The result of running is:

1
2
5
8

Additionally, if you need to sort custom objects, ensure that the object implements the Comparable interface and overrides the compareTo method. Then pass a custom Comparator object to the sort method.

bannerAds