排序是一个很常见的功能,有根据大小正排序,也有逆排序,但有时候需要根据自定义的字段顺序进行排序,下边就是一中方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public class Main { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(); numbers.add(5); numbers.add(4); numbers.add(65);
Integer[] sortOrder = {4,1,5,29,65,33};
Comparator<Integer> customComparator = new Comparator<Integer>() { @Override public int compare(Integer num1, Integer num2) { int index1 = Arrays.asList(sortOrder).indexOf(num1); int index2 = Arrays.asList(sortOrder).indexOf(num2); return Integer.compare(index1, index2); } };
Collections.sort(numbers, customComparator); System.out.println("排序结果:" + numbers); } }
|