Java1.8(Lambda表达式之sort排序)

1.简单的List排序

List list = new ArrayList<>();
list.add(23);
list.add(74);
list.add(11);

----------------stream排序操作(默认ASC排序)

 List collect = list.stream().sorted().collect(Collectors.toList());
System.out.println("list元素正序:" + list);

打印结果:list元素正序:[11, 23, 74]
----------------stream倒序排序操作(DESC排序)

reverseOrder();//反转排序

List collect = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
System.out.println("list元素倒序:" + collect );

打印结果:list元素倒序:[74, 23, 11]
2.复杂的Lisr排序

User u1 = new User("陈一",32);
User u2 = new User("陈二",23);
User u3 = new User("陈三",33);
List users = new ArrayList<>();
users.add(u1);
users.add(u2);
users.add(u3);
//按User的年龄正序排序(默认ASC排序)
List collect users.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());
System.out.println(collect);
打印结果:
[{name = '陈二',age =23},{name = '陈一',age =32},{name = '陈三',age =33}]
//按User的年龄倒序排序(DESC排序)
List collect users.stream().sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList());
System.out.println(collect);
打印结果:
[{name = '陈三',age =33},{name = '陈一',age =32},{name = '陈二',age =23}]

以上就是个人记录下来的一些小操作(觉得可行点个赞?呗)!!!

你可能感兴趣的:(Lambda)