要按照 List 里的顺序对 Java List 对象中的某一个值进行排序,可以使用 Collections.sort() 方法和 Comparator 接口来实现。\n\n首先,创建一个 Comparator 接口的实现类,用来比较 List 中的元素顺序:\n\njava\nimport java.util.Comparator;\nimport java.util.List;\n\npublic class LongComparator implements Comparator<Long> {\n private List<Long> orderList;\n\n public LongComparator(List<Long> orderList) {\n this.orderList = orderList;\n } \n\n @Override\n public int compare(Long o1, Long o2) {\n int index1 = orderList.indexOf(o1);\n int index2 = orderList.indexOf(o2);\n return Integer.compare(index1, index2);\n }\n}\n\n\n然后,在需要排序的 List 对象中,调用 Collections.sort() 方法并传入自定义的 Comparator 对象:\n\njava\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Main {\n public static void main(String[] args) {\n List<Long> orderList = Arrays.asList(3L, 1L, 4L, 2L);\n List<Long> listToSort = new ArrayList<>(Arrays.asList(1L, 2L, 3L, 4L));\n\n Collections.sort(listToSort, new LongComparator(orderList));\n\n System.out.println(listToSort);\n }\n}\n\n\n上述代码中,orderList 是按照需要排序的值的顺序创建的 List 对象。listToSort 是要排序的 List 对象,按照 orderList 中的顺序进行排序后,输出结果为 [3, 1, 4, 2]。

Java List 对象排序:根据特定顺序排列元素

原文地址: https://www.cveoy.top/t/topic/p8mh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录