使用java8 流中的sorted() 方法对元素进行降序排序、升序排序、多字段排序
准备测试数据
// User[id; age; name; Info[salary]] List<User> lists = Lists.newArrayList(); lists.add(new User(1, 24, "张三", new Info("7000"))); lists.add(new User(2, 22, "李四", new Info("8500"))); lists.add(new User(3, 24, "王五", new Info("9000"))); // 整形集合 List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
升序
// 按年龄升序 List<User> userList = lists.stream() .sorted(Comparator.comparing(User::getAge)) .collect(Collectors.toList()); List<Integer> numberList = numbers.stream() .sorted(Comparator.comparing(Integer::intValue)) .collect(Collectors.toList());
降序
// 按年龄降序 List<User> userList = lists.stream() .sorted(Comparator.comparing(User::getAge).reversed()) .collect(Collectors.toList()); List<Integer> numberList = numbers.stream() .sorted(Comparator.comparing(Integer::intValue).reversed()) .collect(Collectors.toList());
多字段排序
// 关键字thenComparing // 1.先以年龄升序 2.当年龄相同时,在以薪资升序 List<User> userList = lists.stream() .sorted(Comparator.comparing(User::getAge).thenComparing(User::getSalary)) .collect(Collectors.toList());
多字段即升序又降序排序
// 关键 thenComparing、Comparator.reverseOrder() // 1.先以年龄升序 2.当年龄相同时,在以薪资降序 List<User> userList = lists.stream() .sorted(Comparator.comparing(User::getAge).thenComparing(User::getSalary,Comparator.reverseOrder())) .collect(Collectors.toList());