使用max和min函数即可,传入一个Comparator比较器,由于Comparator支持常见的Integer、Long等基础数据类型,也支持BigDecimal的比较,所以使用上没啥区别。
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();
//Integer
Optional<User> max = list.stream().max(Comparator.comparing(User::getAge));
max.ifPresent(e -> System.out.println("Integer最大值" + e));
Optional<User> min = list.stream().min(Comparator.comparing(User::getAge));
min.ifPresent(e -> System.out.println("Integer最小值" + e));
//BigDecimal
max = list.stream().max(Comparator.comparing(User::getMoney));
max.ifPresent(e -> System.out.println("BigDecimal最大值" + e));
min = list.stream().min(Comparator.comparing(User::getMoney));
min.ifPresent(e -> System.out.println("BigDecimal最小值" + 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)
Integer最大值User(name=小赵, age=20, money=123.33, birthday=2014-05-18 23:12:29)
Integer最小值User(name=小钱, age=9, money=89.12, birthday=2023-02-18 06:45:12)
BigDecimal最大值User(name=小李, age=13, money=1000.99, birthday=1992-12-04 10:48:08)
BigDecimal最小值User(name=小钱, age=9, money=89.12, birthday=2023-02-18 06:45:12)