本文目录导读:

我来为你详细介绍Java集合排序的多种开发案例,从基础到进阶。
基础排序案例
1 使用Collections.sort()排序
import java.util.*;
public class BasicSortExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(5, 2, 8, 1, 9, 3));
// 升序排序
Collections.sort(numbers);
System.out.println("升序排序: " + numbers);
// 降序排序
Collections.sort(numbers, Collections.reverseOrder());
System.out.println("降序排序: " + numbers);
// 字符串排序
List<String> names = new ArrayList<>(Arrays.asList("张三", "李四", "王五", "赵六"));
Collections.sort(names);
System.out.println("字符串排序: " + names);
}
}
2 使用List.sort()方法
public class ListSortExample {
public static void main(String[] args) {
List<Double> scores = new ArrayList<>(Arrays.asList(85.5, 92.0, 78.5, 95.5, 88.0));
// 升序排序
scores.sort(null);
System.out.println("分数升序: " + scores);
// 降序排序
scores.sort((a, b) -> Double.compare(b, a));
System.out.println("分数降序: " + scores);
}
}
对象排序案例
1 实现Comparable接口
class Student implements Comparable<Student> {
private String name;
private int age;
private double score;
public Student(String name, int age, double score) {
this.name = name;
this.age = age;
this.score = score;
}
// 按年龄排序
@Override
public int compareTo(Student other) {
return Integer.compare(this.age, other.age);
}
@Override
public String toString() {
return String.format("Student{name='%s', age=%d, score=%.1f}", name, age, score);
}
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("张三", 20, 85.5));
students.add(new Student("李四", 22, 92.0));
students.add(new Student("王五", 19, 78.5));
students.add(new Student("赵六", 21, 95.5));
Collections.sort(students);
System.out.println("按年龄排序:");
students.forEach(System.out::println);
}
}
2 使用Comparator接口
import java.util.*;
public class ComparatorExample {
public static void main(String[] args) {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee("E001", "张三", 8000.0, "技术部"));
employees.add(new Employee("E002", "李四", 12000.0, "市场部"));
employees.add(new Employee("E003", "王五", 6000.0, "技术部"));
// 按薪资升序
employees.sort(Comparator.comparingDouble(Employee::getSalary));
System.out.println("按薪资升序:");
employees.forEach(System.out::println);
// 按薪资降序
employees.sort(Comparator.comparingDouble(Employee::getSalary).reversed());
System.out.println("\n按薪资降序:");
employees.forEach(System.out::println);
// 多条件排序:先按部门,再按薪资
employees.sort(Comparator.comparing(Employee::getDepartment)
.thenComparingDouble(Employee::getSalary));
System.out.println("\n按部门和薪资排序:");
employees.forEach(System.out::println);
}
}
class Employee {
private String id;
private String name;
private double salary;
private String department;
// 构造方法、getter/setter省略
public Employee(String id, String name, double salary, String department) {
this.id = id;
this.name = name;
this.salary = salary;
this.department = department;
}
public String getName() { return name; }
public double getSalary() { return salary; }
public String getDepartment() { return department; }
@Override
public String toString() {
return String.format("%s\t%s\t%.0f\t%s", id, name, salary, department);
}
}
高级排序案例
1 自定义排序逻辑
import java.util.*;
public class CustomSortExample {
public static void main(String[] args) {
List<Product> products = new ArrayList<>();
products.add(new Product("手机", 4999.0, 100));
products.add(new Product("电脑", 8999.0, 50));
products.add(new Product("耳机", 299.0, 500));
products.add(new Product("键盘", 399.0, 200));
// 按库存数量降序排序
products.sort((p1, p2) -> Integer.compare(p2.getStock(), p1.getStock()));
System.out.println("按库存数量降序:");
products.forEach(System.out::println);
// 组合排序:先按价格区间,再按销量
products.sort(new ProductComparator());
System.out.println("\n自定义排序:");
products.forEach(System.out::println);
}
}
class Product {
private String name;
private double price;
private int stock;
public Product(String name, double price, int stock) {
this.name = name;
this.price = price;
this.stock = stock;
}
public String getName() { return name; }
public double getPrice() { return price; }
public int getStock() { return stock; }
@Override
public String toString() {
return String.format("%s\t%.0f元\t库存:%d", name, price, stock);
}
}
// 自定义比较器:价格低于500元的优先,然后按库存排序
class ProductComparator implements Comparator<Product> {
@Override
public int compare(Product p1, Product p2) {
boolean p1Cheap = p1.getPrice() < 500;
boolean p2Cheap = p2.getPrice() < 500;
if (p1Cheap != p2Cheap) {
return p1Cheap ? -1 : 1;
}
// 同类价格区间,按库存降序
return Integer.compare(p2.getStock(), p1.getStock());
}
}
2 使用Stream API排序
import java.util.*;
import java.util.stream.Collectors;
public class StreamSortExample {
public static void main(String[] args) {
List<Order> orders = new ArrayList<>();
orders.add(new Order("2024001", "已完成", 1500.0));
orders.add(new Order("2024002", "待支付", 800.0));
orders.add(new Order("2024003", "已完成", 2000.0));
orders.add(new Order("2024004", "已取消", 300.0));
orders.add(new Order("2024005", "待支付", 1200.0));
// 使用Stream流排序
List<Order> sortedOrders = orders.stream()
.sorted(Comparator.comparing(Order::getAmount).reversed())
.collect(Collectors.toList());
System.out.println("按金额降序(Stream API):");
sortedOrders.forEach(System.out::println);
// 复杂排序:按状态分组,每组内按金额排序
Map<String, List<Order>> groupedOrders = orders.stream()
.sorted(Comparator.comparing(Order::getAmount))
.collect(Collectors.groupingBy(Order::getStatus));
System.out.println("\n按状态分组排序:");
groupedOrders.forEach((status, orderList) -> {
System.out.println(status + ":");
orderList.forEach(o -> System.out.println(" " + o));
});
}
}
class Order {
private String orderId;
private String status;
private double amount;
public Order(String orderId, String status, double amount) {
this.orderId = orderId;
this.status = status;
this.amount = amount;
}
public String getOrderId() { return orderId; }
public String getStatus() { return status; }
public double getAmount() { return amount; }
@Override
public String toString() {
return String.format("%s\t状态:%s\t金额:%.0f", orderId, status, amount);
}
}
性能优化案例
1 大数据量排序优化
import java.util.*;
public class PerformanceSortExample {
public static void main(String[] args) {
// 生成测试数据
List<Integer> largeList = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < 1000000; i++) {
largeList.add(random.nextInt(1000000));
}
// 1. 使用并行流排序(大数据量优势明显)
long startTime = System.currentTimeMillis();
List<Integer> parallelSorted = largeList.parallelStream()
.sorted()
.collect(Collectors.toList());
long endTime = System.currentTimeMillis();
System.out.println("并行流排序耗时: " + (endTime - startTime) + "ms");
// 2. 使用Arrays.sort()对数组排序(更快)
startTime = System.currentTimeMillis();
int[] array = largeList.stream().mapToInt(Integer::intValue).toArray();
Arrays.sort(array);
endTime = System.currentTimeMillis();
System.out.println("Arrays.sort()耗时: " + (endTime - startTime) + "ms");
// 3. 使用TreeSet自动排序(适合需要去重的场景)
startTime = System.currentTimeMillis();
SortedSet<Integer> sortedSet = new TreeSet<>(largeList);
endTime = System.currentTimeMillis();
System.out.println("TreeSet排序耗时: " + (endTime - startTime) + "ms");
}
}
实际应用案例
1 排行榜排序系统
import java.util.*;
import java.util.stream.Collectors;
public class RankingSystem {
public static void main(String[] args) {
List<Player> players = new ArrayList<>();
players.add(new Player("选手A", 1500, 85.5));
players.add(new Player("选手B", 1200, 92.0));
players.add(new Player("选手C", 1800, 78.5));
players.add(new Player("选手D", 1500, 90.0));
// 按分数降序,分数相同时按胜率降序
List<Player> ranking = players.stream()
.sorted(Comparator.comparingInt(Player::getScore)
.reversed()
.thenComparingDouble(Player::getWinRate)
.reversed())
.collect(Collectors.toList());
System.out.println("=== 游戏排行榜 ===");
System.out.println("排名\t玩家\t分数\t胜率");
for (int i = 0; i < ranking.size(); i++) {
System.out.printf("%d\t%s\n", i + 1, ranking.get(i));
}
}
}
class Player {
private String name;
private int score;
private double winRate;
public Player(String name, int score, double winRate) {
this.name = name;
this.score = score;
this.winRate = winRate;
}
public String getName() { return name; }
public int getScore() { return score; }
public double getWinRate() { return winRate; }
@Override
public String toString() {
return String.format("%s\t%d\t%.1f%%", name, score, winRate);
}
}
异常处理与最佳实践
1 空值处理
import java.util.*;
public class NullSafeSortExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("C", null, "A", null, "B"));
// 方法1:处理空值,null排在最后
list.sort(Comparator.nullsLast(Comparator.naturalOrder()));
System.out.println("NullsLast: " + list);
// 方法2:处理空值,null排在最前
list.sort(Comparator.nullsFirst(Comparator.naturalOrder()));
System.out.println("NullsFirst: " + list);
// 方法3:自定义空值处理
Comparator<Object> nullSafeComparator = Comparator
.nullsLast((a, b) -> a.toString().compareTo(b.toString()));
list.sort(nullSafeComparator);
System.out.println("自定义: " + list);
}
}
选择合适排序方法的建议:
- 基础类型列表排序:使用
Collections.sort()或list.sort() - 对象排序:实现
Comparable或使用Comparator - 复杂排序需求:使用Lambda表达式或方法引用
- 大数据量排序:考虑使用并行流或
Arrays.sort() - 需要去重排序:使用
TreeSet或TreeMap - 避免空指针:使用
Comparator.nullsFirst()或nullsLast()
这些案例涵盖了Java集合排序的常见场景,你可以根据实际需求选择合适的方案。