List中的对象进行排序处理
以下是使用 Java Stream 对对象列表按 id
和 age
排序的完整示例,包含升序和降序两种场景:
1. 定义测试对象类
@Getter
@Setter
public class Person {private int id;private int age;
}
2. 排序实现代码
import java.util.*;
import java.util.stream.Collectors;public class StreamSortExample {public static void main(String[] args) {List<Person> people = Arrays.asList(new Person(3, 25),new Person(1, 30),new Person(2, 20),);System.out.println("原始列表: " + people);// 升序排序(id优先,age次之)List<Person> ascending = people.stream().sorted(Comparator.comparing(Person::getId).thenComparing(Person::getAge)).collect(Collectors.toList());// 降序排序(id优先,age次之)List<Person> descending = people.stream().sorted(Comparator.comparing(Person::getId, Comparator.reverseOrder()).thenComparing(Person::getAge, Comparator.reverseOrder())).collect(Collectors.toList());System.out.println("升序结果: " + ascending);System.out.println("降序结果: " + descending);}
}
3. 输出结果
原始列表: [Person{id=3, age=25}, Person{id=1, age=30}, Person{id=2, age=20}, Person{id=3, age=20}]
升序结果: [Person{id=1, age=30}, Person{id=2, age=20}, Person{id=3, age=20}, Person{id=3, age=25}]
降序结果: [Person{id=3, age=25}, Person{id=3, age=20}, Person{id=2, age=20}, Person{id=1, age=30}]
注意点说明:
-
排序优先级:
thenComparing()
表示当主排序字段(id)相同时,使用次要字段(age)继续排序- 示例中
id=3
的两个对象会按age
进一步排序
-
升序实现:
Comparator.comparing(Person::getId).thenComparing(Person::getAge)
-
降序实现:
Comparator.comparing(Person::getId, Comparator.reverseOrder()).thenComparing(Person::getAge, Comparator.reverseOrder())
- 每个字段的比较器都需要单独指定排序顺序
- 使用
Comparator.reverseOrder()
明确指定降序
-
扩展性:
- 要添加更多排序字段,继续追加
.thenComparing()
- 要改变排序优先级,调整方法调用顺序即可
- 要添加更多排序字段,继续追加
动态排序,封装成方法块
如果需要运行时动态指定排序规则,可以使用函数式接口:
public static List<Person> sort(List<Person> list, Comparator<Person> comparator) {return list.stream().sorted(comparator).collect(Collectors.toList());
}// 调用示例
sort(people, Comparator.comparing(Person::getId).thenComparing(Person::getAge));
这种方法可以将排序逻辑与具体实现解耦,提高代码复用性。