Java提供了多种方式对数组和集合进行排序和逆序操作。下面我将介绍常用的API操作。

数组排序

1. 基本类型数组排序

int[] intArray = {5, 2, 9, 1, 5};

// 升序排序
Arrays.sort(intArray); // [1, 2, 5, 5, 9]

// 降序排序(需要转换为包装类数组)
Integer[] integerArray = {5, 2, 9, 1, 5};
Arrays.sort(integerArray, Collections.reverseOrder()); // [9, 5, 5, 2, 1]

2. 对象数组排序

String[] strArray = {"banana", "apple", "pear", "orange"};

// 升序排序
Arrays.sort(strArray); // ["apple", "banana", "orange", "pear"]

// 降序排序
Arrays.sort(strArray, Collections.reverseOrder()); // ["pear", "orange", "banana", "apple"]

// 自定义排序(按字符串长度)
Arrays.sort(strArray, (a, b) -> a.length() - b.length());

集合排序

1. List排序

List<Integer> list = new ArrayList<>(Arrays.asList(5, 2, 9, 1, 5));

// 升序排序
Collections.sort(list); // [1, 2, 5, 5, 9]

// 降序排序
Collections.sort(list, Collections.reverseOrder()); // [9, 5, 5, 2, 1]

// Java 8+ 使用Stream API排序
List<Integer> sortedList = list.stream()
    .sorted() // 升序
    .collect(Collectors.toList());

List<Integer> reverseSortedList = list.stream()
    .sorted(Comparator.reverseOrder()) // 降序
    .collect(Collectors.toList());

2. 自定义对象排序

class Person {
    String name;
    int age;
    // 构造方法、getter/setter省略
}

List<Person> people = new ArrayList<>();
// 添加人员...

// 按年龄升序排序
Collections.sort(people, (p1, p2) -> p1.getAge() - p2.getAge());

// 按姓名升序排序
Collections.sort(people, (p1, p2) -> p1.getName().compareTo(p2.getName()));

// Java 8+ 方法引用方式
Collections.sort(people, Comparator.comparingInt(Person::getAge));
people.sort(Comparator.comparing(Person::getName));
public class helloword {
    class  student{
        String name;
        int age;
        student(String name, int age){
            this.name = name;
            this.age = age;
        }
    }
    public static void main(String[] args) {
     int [] arr = new int[10];
        List<student> list = new ArrayList<>();
        Collections.sort(list, new Comparator<student>() {
            @Override
            public int compare(student o1, student o2) {
                int number  = o1.age - o2.age;
                return number==0?o1.name.compareTo(o2.name):number;
            }
        });
    }
}

其他排序技巧

1. 部分数组排序

int[] array = {5, 2, 9, 1, 5, 6, 3};
// 只排序前4个元素
Arrays.sort(array, 0, 4); // [1, 2, 5, 9, 5, 6, 3]

2. 并行排序(大数据量)

int[] largeArray = new int[1000000];
// 使用并行排序算法
Arrays.parallelSort(largeArray);

3. 保持原始数组并返回排序副本

int[] original = {5, 2, 9, 1, 5};
int[] sortedCopy = Arrays.copyOf(original, original.length);
Arrays.sort(sortedCopy);
  1. Arrays.sort()对于基本类型使用快速排序,对于对象类型使用归并排序

  2. Collections.sort()底层调用的是List.sort()方法

  3. Java 7+开始,对象排序使用TimSort算法

  4. 逆序操作会修改原始数组/集合,如果需要保留原始数据,应先创建副本