如何使用 Java 中的比较器按降序对 List 进行排序
请首先创建一个 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]
广告