sql中可以使用 order by 对数据进行排序,java 也可以直接对list排序,而且还有很多种方式
1.Collections 排序
正序
Collections.sort(list, new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
return o1.getAge().compareTo(o2.getAge());
}
});
倒序
Collections.reverse(list);
2.Collections + lambda表达式
JDK8支持lambda表达式,写法更加简洁:
Collections.sort(list, (o1, o2) -> o1.getAge().compareTo(o2.getAge()));
3.使用Comparator接口:
Collections.sort(list, Comparator.comparing(Employee::getAge));
倒序:
Collections.sort(list, Comparator.comparing(Employee::getAge).reversed());
4.stream的sorted方法
也是java 8的新特性
list.stream().sorted(Comparator.comparing(Employee::getAge));
倒序:
list.stream().sorted(Comparator.comparing(Employee::getAge).reversed());
5.list自带的sort方法
list.sort(Comparator.comparing(Employee::getAge));
倒序:
list.sort(Comparator.comparing(Employee::getAge).reversed());