自学内容网 自学内容网

【JAVA】Hutool CollUtil.sort 方法:多场景下的排序解决方案

在 Java 开发中,集合的排序是常见需求。Hutool 库的 CollUtil.sort 方法提供了一系列用于排序的实用功能,适用于不同的场景。以下是对几种常见场景及其实现方式的总结:

<dependency>
<groupId>org.dromara.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>6.0.0-M14</version>
</dependency>

1. 默认升序排序

对于简单的升序排序,可以直接使用 CompareUtil.natural 获取自然顺序比较器,并结合 CollUtil.sort 方法实现:

List < String > list = ListUtil.of("banana", "apple", "orange");
List < String > sortedList = CollUtil.sort(list, CompareUtil.natural());

2. 默认降序排序

如果需要进行降序排序,可以结合 CompareUtil.naturalReverse 获取逆序比较器,并使用 CollUtil.sort 方法进行排序:

List < String > list = ListUtil.of("banana", "apple", "orange");
List < String > sortedList = CollUtil.sort(list, CompareUtil.naturalReverse());

3. 字符串长度排序逻辑

当需要基于自定义逻辑进行排序时,可以使用 Hutool 提供的 StrLengthComparator 等已定义的比较器,或者通过以下方式自定义比较器:

List < String > list = ListUtil.of("banana", "apple", "orange");
// 短在前
List < String > sortedList = CollUtil.sort(list, StrLengthComparator.INSTANCE);
// 短在后
List < String > sortedList2 = CollUtil.sort(list, StrLengthComparator.INSTANCE.reversed());

4. 带有null值排序

当集合中包含 null 值时,可以使用 Comparator.nullsLastComparator.nullsFirst 方法将 null 值排序到列表的一端:

List < String > list = ListUtil.of(null, "banana", "apple", "orange");
List < String > sortedList = CollUtil.sort(list, Comparator.nullsLast(Comparator.naturalOrder()));
System.out.println(sortedList);

或者

List < String > list = ListUtil.of("banana", "apple", "orange", null);
List < String > sortedList = CollUtil.sort(list, Comparator.nullsFirst(Comparator.naturalOrder()));
System.out.println(sortedList);

5. 对象字段排序

对于对象集合的排序,可以使用 FieldsComparator 或其他比较器对多个字段进行排序:

List < Person > people = ListUtil.of(new Person("Alice", null),
        new Person("Bob", 28),
        new Person("Charlie", 25));
List < Person > sorted = CollUtil.sort(people, new FieldComparator<>(Person.class, "age"));
System.out.println(sorted);

或者CompareUtil实现排序逻辑:

List < Person > people = ListUtil.of(new Person("Alice", null), new Person("Bob", 25),
                new Person("Charlie", 25));
// 自然比较两个对象的大小,isNullGreater – null值是否做为最大值
List < Person > sort = CollUtil.sort(people,
(compareOne, compareTow) -> CompareUtil.compare(compareOne.getAge(), compareTow.getAge(), true));
System.out.println(sort);

年龄相同按照姓名排序

List < Person > people = ListUtil.of(new Person("Alice", null),
new Person("Bob", 25),
new Person("Charlie", 25));
List < Person > sorted2 = CollUtil.sort(people, new FieldsComparator<>(Person.class, "age", "name"));
System.out.println(sorted2);

总结:
Hutool 的 CollUtil.sort 方法为 Java 开发者提供了一系列强大的排序功能,能够满足各种场景下的排序需求。通过合理选择和使用这些功能,可以显著提高代码的可读性和可维护性。


原文地址:https://blog.csdn.net/hs598375774/article/details/140641770

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!