准备工作,新建一个User类
使用stream排序操作(默认ASC排序)
stream倒序排序操作
sorted(Comparator.reverseOrder())
代码例子:
/*** lambda* sorted排序*/@Testpublic void test19() {List<Integer> list = new ArrayList<>();list.add(1);list.add(11);list.add(111);list.add(9);List<Integer> collect = list.stream().sorted().collect(Collectors.toList());collect.forEach(System.out::println);System.out.println("********");List<Integer> reverseOrder = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());reverseOrder.forEach(System.out::println);}
操作对象中属性的排序
List<User> user = new ArrayList<>();user.add(new User(1L, 18, "小明"));user.add(new User(2L, 20, "小王"));user.add(new User(3L, 28, "小刚"));user.add(new User(4l, 25, "小丽"));List<User> collect1 = user.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());collect1.forEach(e -> {System.out.println(JSON.toJSONString(e));});System.out.println("***************");List<User> collect2 = user.stream().sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList());collect2.forEach(e -> {System.out.println(JSON.toJSONString(e));});
先按照age排序,age相同时按照id排序
//先按照age排序,age相同时按照id排序List<User> collect3 = user.stream().sorted(Comparator.comparing(User::getAge).thenComparing(User::getId)).collect(Collectors.toList());collect3.forEach(e -> {System.out.println(JSON.toJSONString(e));});