说明
我们在按List排序时会通过这样来:
-
首先定义一个类 @Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class User {
private String name;
private Integer age;
}
-
模拟一些数据 List<User> userList = new ArrayList();
userList.add(new User(null, 1));
userList.add(new User("", 1));
userList.add(new User("1", 12));
userList.add(new User("11", 12));
userList.add(new User("2", 12));
userList.add(new User("12", 12));
-
正常按年龄来排序 List<User> sortByAgeList =userList.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());
倒序: userList.stream().sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList());
但是我们按照字符串来排序或者其它类型会希望来自定义排序的问题,可以自定义排序来实现
自定义排序方法
List<User> collect = userList.stream().sorted(Comparator.comparing(User::getName, (x, y) -> {
if (StringUtils.isNotBlank(x) && StringUtils.isNotBlank(y)) {
return Integer.valueOf(x) > Integer.valueOf(y) ? 1 : -1;
}
return -1;
})).collect(Collectors.toList());
System.out.println(JSON.toJSONString(collect));
输出结果:
[{"age":12,"name":"1"},{"age":12,"name":"2"},{"age":12,"name":"11"},{"age":12,"name":"12"},{"age":1,"name":""},{"age":1}]
Process finished with exit code 0
|