JAVA8-Lambda-(sorted+Comparator)排序
使用场景:排队的时候按照个子大小排队
使用API
排序和MySql中的升序降序规则一样。
在排序时需要注意的是降序需要用到reversed();
public static void main(String[] args) {
ArrayList<People> list = new ArrayList<>();
list.add(new People("张三", 191, "杭州"));
list.add(new People("李四", 182, "海口"));
list.add(new People("王五", 173, "西安"));
list.add(new People("赵六", 162, "兰州"));
list.add(new People("二狗", 111, "杭州"));
list.add(new People("铁柱", 171, "海口"));
//按照身高排序(升序)
List<People> PeopleAscList = list.stream()
.sorted(Comparator.comparing(People::getHeight))
.collect(Collectors.toList());
System.out.println("按照身高排序(升序):" + PeopleAscList);
//按照身高排序(降序)
List<People> PeopleDescList = list.stream()
.sorted(Comparator.comparing(People::getHeight).reversed())
.collect(Collectors.toList());
System.out.println("按照身高排序(降序):" + PeopleDescList);
}
输出结果:
按照身高排序(升序):[Student{name='二狗', height=111, addr='杭州'}, Student{name='赵六', height=162, addr='兰州'}, Student{name='铁柱', height=171, addr='海口'}, Student{name='王五', height=173, addr='西安'}, Student{name='李四', height=182, addr='海口'}, Student{name='张三', height=191, addr='杭州'}]
按照身高排序(降序):[Student{name='张三', height=191, addr='杭州'}, Student{name='李四', height=182, addr='海口'}, Student{name='王五', height=173, addr='西安'}, Student{name='铁柱', height=171, addr='海口'}, Student{name='赵六', height=162, addr='兰州'}, Student{name='二狗', height=111, addr='杭州'}]