java中使用sort实现为集合排序
遇到一个需求是需要把从数据库拿到的数据进行再次排序,查询资料后发现使用 sort 方法可以做到,现在记录一下。
从数据库拿到的数据结构大致如下:
id | name | math | verbal | english | total |
---|---|---|---|---|---|
001 | 张三 | 80 | 80 | 80 | 240 |
002 | 李四 | 83 | 83 | 83 | 249 |
003 | 王五 | 70 | 70 | 70 | 210 |
004 | 赵六 | 90 | 90 | 90 | 270 |
005 | 孙七 | 81 | 81 | 81 | 243 |
在这里添加一些假的数据:
public List<Student> studentCS() {
Student student1 = new Student("001","张三","80","80","80","240");
Student student2 = new Student("002","李四","83","83","83","249");
Student student3 = new Student("003","王五","70","70","70","210");
Student student4 = new Student("004","赵六","90","90","90","270");
Student student5 = new Student("005","孙七","81","81","81","243");
List<Student> studentList = new ArrayList<>();
studentList.add(student1);
studentList.add(student2);
studentList.add(student3);
studentList.add(student4);
studentList.add(student5);
// for循环是为了输出好看,没有实际功能作用
for (Student s:studentList) {
System.out.println(s);
}
return studentList;
}
下面是没有排序的输出结果:
sort 方法的使用方法:
集合名.sort(Comparator.comparing(类名::get要排序的某个属性));
注意:貌似这个类中必须要有get,set方法,才可以使用 sort 进行排序
按照 total 字段排序,实例如下:
public List<Student> studentCS() {
Student student1 = new Student("001","张三","80","80","80","240");
Student student2 = new Student("002","李四","83","83","83","249");
Student student3 = new Student("003","王五","70","70","70","210");
Student student4 = new Student("004","赵六","90","90","90","270");
Student student5 = new Student("005","孙七","81","81","81","243");
List<Student> studentList = new ArrayList<>();
studentList.add(student1);
studentList.add(student2);
studentList.add(student3);
studentList.add(student4);
studentList.add(student5);
//这里是重点
studentList.sort(Comparator.comparing(Student::getTotal));
for (Student s:studentList) {
System.out.println(s);
}
return studentList;
}
下面为按照 total 字段进行排序后的输出结果,默认为升序排序。
下面是按照 total 字段降序排序的使用方法,只需要在排序的字段后面加上 .reversed()
即可
public List<Student> studentCS() {
Student student1 = new Student("001","张三","80","80","80","240");
Student student2 = new Student("002","李四","83","83","83","249");
Student student3 = new Student("003","王五","70","70","70","210");
Student student4 = new Student("004","赵六","90","90","90","270");
Student student5 = new Student("005","孙七","81","81","81","243");
List<Student> studentList = new ArrayList<>();
studentList.add(student1);
studentList.add(student2);
studentList.add(student3);
studentList.add(student4);
studentList.add(student5);
studentList.sort(Comparator.comparing(Student::getTotal).reversed());
for (Student s:studentList) {
System.out.println(s);
}
return studentList;
}
降序排序的显示结果:
.
.
.
.
.
感谢阅读,有不足之处欢迎指出,共同探讨