Java中获取集合最大值首选Collections.max(),需元素实现Comparable接口或传入Comparator;Stream API更灵活但返回Optional需处理空值;数组需先转流或用IntStream/第三方库。
Java里找集合中最大值,最直接的方式是用 Collections.max() 方法,但要注意集合元素必须实现 Comparable 接口(比如 Integer、String),否则会抛 ClassCastException 或 UnsupportedOperationException。
适用于 List、ArrayList、LinkedList 等实现了 Collection 接口的集合:
Collections.max(list),返回最大元素NoSuchElementException,建议先判空Collections.ma
x(list, Comparator.naturalOrder()) 或 Comparator.reverseOrder()
示例:
List更灵活,适合链式操作或需过滤/转换后再取最大值的场景:
list.stream().max(Comparator.naturalOrder()) 返回 Optional
.orElse(null) 或 .orElseThrow()
map() 先提取字段,比如找对象中某个属性的最大值示例:
Optional比如 List
Collections.max(people, Comparator.comparing(p -> p.getAge()))
people.stream().max(Comparator.comparing(Person::getAge)).orElse(null)
数组不是集合,不能直接用 Collections.max():
Arrays.stream(arr).boxed().max(Integer::compare).orElse(null)
Arrays.stream(arr).max().orElse(-1)(仅限 int[])ArrayUtils.max(int[]),更简洁基本上就这些。选 Collections.max() 最简单,Stream 更函数化且扩展性强,注意空值和类型兼容性就行。