1、测试数据
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private int id;
private int age;
private String name;
private BigDecimal money;
}
private static List<User> getList() {
List<User> users = new ArrayList<>();
users.add(new User(1, 28, "张三", new BigDecimal(4000)));
users.add(new User(2, 21, "李四", new BigDecimal(5000)));
users.add(new User(3, 24, "王五", new BigDecimal(6000)));
users.add(new User(4, 23, "赵六", new BigDecimal(7000)));
return users;
}
2、升序
List<User> ascUsersByAge = getList().stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());
3、降序
List<User> descUsersByAge = getList().stream().sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList());
4、组合排序
List<User> orderUsersByAgeAndMoney = getList().stream().sorted(Comparator.comparing(User::getAge).thenComparing(User::getMoney)).collect(Collectors.toList());