java stream api 中的 sorted() 方法是一个强大的中间操作,它允许我们对流中的元素进行排序。默认情况下,sorted() 要求元素实现 comparable 接口,但在实际应用中,我们经常需要根据特定业务规则进行自定义排序。本文将深入探讨如何使用 sorted() 方法实现自定义排序,涵盖各种常见场景和高级技巧。
一、sorted 方法基础
java stream 提供了两种 sorted() 方法重载:
自然排序:要求元素实现 comparable 接口
stream<t> sorted()
自定义排序:通过 comparator 指定排序规则
stream<t> sorted(comparator<? super t> comparator)
二、自定义排序的基本实现
1. 使用 lambda 表达式创建 comparator
// 示例1:按字符串长度排序
list<string> words = arrays.aslist("apple", "banana", "cherry", "date");
list<string> sortedbylength = words.stream()
.sorted((s1, s2) -> s1.length() - s2.length())
.tolist();
system.out.println(sortedbylength); // 输出:[date, apple, cherry, banana]
// 示例2:按绝对值大小排序
list<integer> numbers = arrays.aslist(-5, 2, -8, 1, 3);
list<integer> sortedbyabs = numbers.stream()
.sorted((n1, n2) -> math.abs(n1) - math.abs(n2))
.tolist();
system.out.println(sortedbyabs); // 输出:[1, 2, 3, -5, -8]2. 使用 comparator 静态方法简化代码
java 8 为 comparator 接口提供了许多实用的静态方法,使排序代码更加简洁:
// 使用 comparator.comparing 方法
list<string> sortedbylength2 = words.stream()
.sorted(comparator.comparing(string::length))
.tolist();
// 使用 comparator.comparingint 优化基本类型比较
list<integer> sortedbyabs2 = numbers.stream()
.sorted(comparator.comparingint(math::abs))
.tolist();三、处理复杂对象排序
1. 对自定义对象按属性排序
class person {
private string name;
private int age;
private localdate birthdate;
// 构造方法、getter和setter略
@override
public string tostring() {
return "person{name='" + name + "', age=" + age + ", birthdate=" + birthdate + "}";
}
}
// 按年龄升序排序
list<person> people = arrays.aslist(
new person("alice", 25, localdate.of(2000, 1, 1)),
new person("bob", 20, localdate.of(2005, 5, 5)),
new person("charlie", 30, localdate.of(1995, 10, 10))
);
list<person> sortedbyage = people.stream()
.sorted(comparator.comparingint(person::getage))
.tolist();
system.out.println(sortedbyage);
// 输出:[person{name='bob', age=20}, person{name='alice', age=25}, person{name='charlie', age=30}]2. 多条件排序(复合排序)
使用 thencomparing() 方法可以实现多级排序:
// 先按年龄升序,年龄相同则按出生日期降序
list<person> sortedbyageandbirthdate = people.stream()
.sorted(comparator.comparingint(person::getage)
.thencomparing(person::getbirthdate, comparator.reverseorder()))
.tolist();
system.out.println(sortedbyageandbirthdate);四、处理空值与 null 安全排序
1. 空值处理策略
在实际应用中,集合元素或元素属性可能为 null,直接排序会导致 nullpointerexception。我们可以使用 comparator.nullsfirst() 或 comparator.nullslast() 来安全处理 null 值:
// 示例:处理可能为 null 的字符串
list<string> stringswithnulls = arrays.aslist("apple", null, "banana", null, "cherry");
// null 值排在前面
list<string> sortedwithnullsfirst = stringswithnulls.stream()
.sorted(comparator.nullsfirst(comparator.naturalorder()))
.tolist();
system.out.println(sortedwithnullsfirst);
// 输出:[null, null, apple, banana, cherry]
// null 值排在后面
list<string> sortedwithnullslast = stringswithnulls.stream()
.sorted(comparator.nullslast(comparator.naturalorder()))
.tolist();
system.out.println(sortedwithnullslast);
// 输出:[apple, banana, cherry, null, null]2. 对象属性可能为 null 的情况
class product {
private string name;
private double price; // 价格可能为 null
// 构造方法、getter和setter略
}
list<product> products = arrays.aslist(
new product("laptop", 1200.0),
new product("mouse", null),
new product("keyboard", 50.0)
);
// 按价格排序,null 价格排在最后
list<product> sortedbyprice = products.stream()
.sorted(comparator.comparing(product::getprice, comparator.nullslast(double::compare)))
.tolist();五、逆序排序与自定义比较逻辑
1. 逆序排序
使用 comparator.reverseorder() 或 comparator.comparing().reversed() 实现逆序:
// 字符串长度逆序排序
list<string> reversedbylength = words.stream()
.sorted(comparator.comparing(string::length).reversed())
.tolist();
// 另一种逆序写法
list<string> reversedbylength2 = words.stream()
.sorted((s1, s2) -> s2.length() - s1.length())
.tolist();2. 自定义复杂比较逻辑
对于更复杂的业务规则,可以实现 comparator 接口:
// 示例:按字符串长度排序,长度相同则按字母顺序排序
list<string> complexsort = words.stream()
.sorted(new comparator<string>() {
@override
public int compare(string s1, string s2) {
int lengthcompare = integer.compare(s1.length(), s2.length());
if (lengthcompare != 0) {
return lengthcompare;
}
return s1.compareto(s2);
}
})
.tolist();
// 使用 lambda 简化
list<string> complexsort2 = words.stream()
.sorted((s1, s2) -> {
int lengthcompare = integer.compare(s1.length(), s2.length());
return lengthcompare != 0 ? lengthcompare : s1.compareto(s2);
})
.tolist();六、性能优化与注意事项
1. 基本类型与装箱类型
对于基本类型(如 int、long、double),优先使用 comparingint、comparinglong、comparingdouble 避免装箱拆箱开销:
// 性能优化示例
list<integer> numbers = arrays.aslist(5, 3, 8, 1, 2);
// 避免装箱
list<integer> optimizedsort = numbers.stream()
.sorted(comparator.comparingint(integer::intvalue))
.tolist();2. 排序稳定性
stream.sorted() 使用的是稳定排序算法(timsort),即相等元素的相对顺序不会改变。这在多级排序中尤为重要:
// 示例:先按部门排序,再按工资排序
list<employee> employees = ...;
list<employee> sortedemployees = employees.stream()
.sorted(comparator.comparing(employee::getdepartment)
.thencomparingdouble(employee::getsalary))
.tolist();3. 并行流排序性能
在并行流中,排序操作可能会导致性能下降,因为需要全局数据重组。谨慎在并行流中使用复杂排序:
// 并行流排序示例
list<integer> parallelsorted = numbers.parallelstream()
.sorted()
.tolist();
七、实战案例
1. 电商商品排序系统
class product {
private string name;
private double price;
private int salesvolume;
private localdatetime createtime;
// 构造方法、getter和setter略
}
// 按价格升序排序
list<product> sortedbyprice = products.stream()
.sorted(comparator.comparingdouble(product::getprice))
.tolist();
// 按销量降序,销量相同则按创建时间降序
list<product> sortedbysalesandtime = products.stream()
.sorted(comparator.comparingint(product::getsalesvolume).reversed()
.thencomparing(product::getcreatetime, comparator.reverseorder()))
.tolist();2. 日志时间戳排序
class logentry {
private localdatetime timestamp;
private string message;
private loglevel level;
// 构造方法、getter和setter略
}
// 按时间戳排序
list<logentry> sortedlogs = logs.stream()
.sorted(comparator.comparing(logentry::gettimestamp))
.tolist();
// 按日志级别排序(自定义顺序:error > warn > info > debug)
list<logentry> sortedbylevel = logs.stream()
.sorted(comparator.comparing(logentry::getlevel,
comparator.comparingint(level -> {
switch (level) {
case error: return 4;
case warn: return 3;
case info: return 2;
case debug: return 1;
default: return 0;
}
}).reversed()))
.tolist();八、总结与最佳实践
优先使用方法引用和静态工具方法:
// 推荐写法 sorted(comparator.comparing(person::getage)) // 避免冗余的 lambda sorted((p1, p2) -> p1.getage() - p2.getage())
多级排序使用链式调用:
sorted(comparator.comparing(person::getdepartment)
.thencomparing(person::getage)
.thencomparing(person::getname))
处理 null 值:
sorted(comparator.nullslast(comparator.comparing(person::getname)))
基本类型优化:
sorted(comparator.comparingint(person::getage)) // 避免装箱
复杂比较器提取为常量:
public static final comparator<person> age_name_comparator =
comparator.comparingint(person::getage)
.thencomparing(person::getname);
// 使用时
sorted(age_name_comparator)通过掌握 sorted() 方法的各种用法,你可以灵活应对各种复杂的排序需求,编写出简洁、高效且易于维护的代码。在实际开发中,合理运用 comparator 的各种工具方法和特性,能够显著提升代码质量和开发效率。
到此这篇关于java stream 的 sorted 方法实现自定义排序全解析的文章就介绍到这了,更多相关java stream sorted方法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论