让我们首先创建一个ArrayList-
ArrayList<Integer>arrList = new ArrayList<Integer>(); arrList.add(10); arrList.add(50); arrList.add(100); arrList.add(150); arrList.add(250);
使用Comparators接口以相反的顺序排序reverseOrder()
-
Comparator comparator = Collections.reverseOrder(); Now, sort with Collections: Collections.sort(arrList, comparator);
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class Demo { public static void main(String[] args) { ArrayList<Integer>arrList = new ArrayList<Integer>(); arrList.add(10); arrList.add(50); arrList.add(100); arrList.add(150); arrList.add(250); arrList.add(100); arrList.add(150); arrList.add(250); Comparator comparator = Collections.reverseOrder(); System.out.println("List = "+arrList); Collections.sort(arrList, comparator); System.out.println("Sorted List in descending order = "+arrList); } }
输出结果
List = [10, 50, 100, 150, 250, 100, 150, 250] Sorted List in descending order = [250, 250, 150, 150, 100, 100, 50, 10]