Stream流取最早、最晚时间

Stream流取最大值、最小值一样的实现方式。Date类型本质上是一个时间戳,也就是数值类型,即:最早时间=最小值、最晚时间=最大值。

public class Test {

    public static void main(String[] args) {
        List<User> list = Arrays.asList(
                new User("小赵", 20, new BigDecimal("123.33"), DateUtil.parseDateTime("2014-5-18 23:12:29")),
                new User("小钱", 9, new BigDecimal("89.12"), DateUtil.parseDateTime("2023-2-18 06:45:12")),
                new User("小孙", 18, new BigDecimal("280.28"), DateUtil.parseDateTime("2009-3-31 16:33:45")),
                new User("小李", 13, new BigDecimal("1000.99"), DateUtil.parseDateTime("1992-12-4 10:48:08"))
        );
        list.forEach(System.out::println);
        System.out.println();

        //Date
        Optional<User> max = list.stream().max(Comparator.comparing(User::getBirthday));
        max.ifPresent(e -> System.out.println("Date最晚时间" + e));
        Optional<User> min = list.stream().min(Comparator.comparing(User::getBirthday));
        min.ifPresent(e -> System.out.println("Date最早时间" + e));
    }

}

@Data
@ToString
@AllArgsConstructor
class User {

    private String name;

    private Integer age;

    private BigDecimal money;

    private Date birthday;

}
User(name=小赵, age=20, money=123.33, birthday=2014-05-18 23:12:29)
User(name=小钱, age=9, money=89.12, birthday=2023-02-18 06:45:12)
User(name=小孙, age=18, money=280.28, birthday=2009-03-31 16:33:45)
User(name=小李, age=13, money=1000.99, birthday=1992-12-04 10:48:08)

Date最晚时间User(name=小钱, age=9, money=89.12, birthday=2023-02-18 06:45:12)
Date最早时间User(name=小李, age=13, money=1000.99, birthday=1992-12-04 10:48:08)

觉得内容还不错?打赏个钢镚鼓励鼓励!!👍