Stream流取最大值、最小值

使用max和min函数即可,传入一个Comparator比较器,由于Comparator支持常见的Integer、Long等基础数据类型,也支持BigDecimal的比较,所以使用上没啥区别。

折叠复制代码
  1. public class Test {
  2. public static void main(String[] args) {
  3. List<User> list = Arrays.asList(
  4. new User("小赵", 20, new BigDecimal("123.33"), DateUtil.parseDateTime("2014-5-18 23:12:29")),
  5. new User("小钱", 9, new BigDecimal("89.12"), DateUtil.parseDateTime("2023-2-18 06:45:12")),
  6. new User("小孙", 18, new BigDecimal("280.28"), DateUtil.parseDateTime("2009-3-31 16:33:45")),
  7. new User("小李", 13, new BigDecimal("1000.99"), DateUtil.parseDateTime("1992-12-4 10:48:08"))
  8. );
  9. list.forEach(System.out::println);
  10. System.out.println();
  11. //Integer
  12. Optional<User> max = list.stream().max(Comparator.comparing(User::getAge));
  13. max.ifPresent(e -> System.out.println("Integer最大值" + e));
  14. Optional<User> min = list.stream().min(Comparator.comparing(User::getAge));
  15. min.ifPresent(e -> System.out.println("Integer最小值" + e));
  16. //BigDecimal
  17. max = list.stream().max(Comparator.comparing(User::getMoney));
  18. max.ifPresent(e -> System.out.println("BigDecimal最大值" + e));
  19. min = list.stream().min(Comparator.comparing(User::getMoney));
  20. min.ifPresent(e -> System.out.println("BigDecimal最小值" + e));
  21. }
  22. }
  23. @Data
  24. @ToString
  25. @AllArgsConstructor
  26. class User {
  27. private String name;
  28. private Integer age;
  29. private BigDecimal money;
  30. private Date birthday;
  31. }
折叠复制代码
  1. User(name=小赵, age=20, money=123.33, birthday=2014-05-18 23:12:29)
  2. User(name=小钱, age=9, money=89.12, birthday=2023-02-18 06:45:12)
  3. User(name=小孙, age=18, money=280.28, birthday=2009-03-31 16:33:45)
  4. User(name=小李, age=13, money=1000.99, birthday=1992-12-04 10:48:08)
  5. Integer最大值User(name=小赵, age=20, money=123.33, birthday=2014-05-18 23:12:29)
  6. Integer最小值User(name=小钱, age=9, money=89.12, birthday=2023-02-18 06:45:12)
  7. BigDecimal最大值User(name=小李, age=13, money=1000.99, birthday=1992-12-04 10:48:08)
  8. BigDecimal最小值User(name=小钱, age=9, money=89.12, birthday=2023-02-18 06:45:12)

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