How can you sort a list in Java from largest to smallest?

You can use the sort() method in the Collections class to achieve sorting from largest to smallest. Here is an example code:

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

public class Main {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(5);
        list.add(3);
        list.add(8);
        list.add(2);
        
        // 使用Collections.sort()方法进行排序
        Collections.sort(list, Collections.reverseOrder());
        
        System.out.println("从大到小排序后的list: " + list);
    }
}

Output result:

从大到小排序后的list: [8, 5, 3, 2]

The first parameter in the sort() method is the list to be sorted, while the second parameter is a Comparator object. The Collections.reverseOrder() method returns a Comparator object that can be used to sort in descending order.

bannerAds