1. 概述
在本教程中,我们将探讨如何对 Java 数组进行升序和降序排序。
我们会使用 Java 内置的 Arrays
工具类进行排序,同时也会介绍如何通过自定义 Comparator
来实现更复杂的排序逻辑。
2. 示例对象定义
在开始之前,我们先定义几个用于演示的数组:
✅ 基本类型数组(int 和 String):
int[] numbers = new int[] { -8, 7, 5, 9, 10, -2, 3 };
String[] strings = new String[] { "learning", "java", "with", "baeldung" };
✅ 自定义对象数组(Employee 类):
Employee john = new Employee(6, "John");
Employee mary = new Employee(3, "Mary");
Employee david = new Employee(4, "David");
Employee[] employees = new Employee[] { john, mary, david };
⚠️ 注意:Employee 类需实现
Comparable
接口或提供字段访问方法,如getName()
和getId()
。
3. 升序排序
Java 的 java.util.Arrays.sort()
方法可以快速实现数组的升序排序,支持基本类型和实现了 Comparable
接口的对象。
3.1. 基本类型排序
直接调用 Arrays.sort()
方法即可完成升序排序:
Arrays.sort(numbers);
assertArrayEquals(new int[] { -8, -2, 3, 5, 7, 9, 10 }, numbers);
✅ 内部使用的是 双轴快排(Dual-Pivot Quicksort) 算法,性能优异。
3.2. 实现了 Comparable 的对象排序
对于实现了 Comparable
接口的对象数组(如 String),同样可以直接使用 Arrays.sort()
:
Arrays.sort(strings);
assertArrayEquals(new String[] { "baeldung", "java", "learning", "with" }, strings);
3.3. 未实现 Comparable 的对象排序
对于未实现 Comparable
接口的对象(如 Employee),我们需要自定义 Comparator
:
Arrays.sort(employees, Comparator.comparing(Employee::getName));
assertArrayEquals(new Employee[] { david, john, mary }, employees);
📌 如果需要多字段排序,可以使用 thenComparing
方法:
Arrays.sort(employees, Comparator.comparing(Employee::getName).thenComparing(Employee::getId));
4. 降序排序
4.1. 基本类型降序排序
由于 Java 不允许对基本类型使用 Comparator
,因此不能直接降序排序。但我们有以下几种变通方法:
方法一:先升序排序再反转数组
Arrays.sort(numbers);
// 然后手动反转数组
方法二:使用 Guava 的 Lists.reverse()
List<Integer> list = Arrays.stream(numbers).boxed().collect(Collectors.toList());
Collections.reverse(list);
numbers = list.stream().mapToInt(Integer::intValue).toArray();
方法三:使用 Stream 一行搞定 ✅(推荐)
numbers = IntStream.of(numbers)
.boxed()
.sorted(Comparator.reverseOrder())
.mapToInt(Integer::intValue)
.toArray();
assertArrayEquals(new int[] { 10, 9, 7, 5, 3, -2, -8 }, numbers);
📌 原理是将 int
装箱为 Integer
,使其支持 Comparator
接口。
4.2. 实现了 Comparable 的对象降序排序
只需添加 Comparator.reverseOrder()
参数即可:
Arrays.sort(strings, Comparator.reverseOrder());
assertArrayEquals(new String[] { "with", "learning", "java", "baeldung" }, strings);
4.3. 未实现 Comparable 的对象降序排序
只需在自定义 Comparator
后追加 .reversed()
:
Arrays.sort(employees, Comparator.comparing(Employee::getName).reversed());
assertArrayEquals(new Employee[] { mary, john, david }, employees);
5. 总结
本文总结了在 Java 中对数组进行升序和降序排序的各种方式:
- 基本类型使用
Arrays.sort()
升序,降序需借助Stream
或反转。 - 实现
Comparable
的对象可直接排序,降序使用Comparator.reverseOrder()
。 - 自定义对象排序使用
Comparator.comparing()
,支持链式调用实现多字段排序。
📌 源码示例可从 GitHub 项目地址 获取。