最常用方式是使用Collections.max()和Collections.min()方法,适用于实现Collection接口的集合类。若元素实现Comparable接口(如Integer、String),可直接调用;自定义比较规则则传入Comparator,如按字符串长度或对象属性比较。示例中查找数字集合的最大最小值,字符串列表的最长最短串,以及Person对象中年龄最大最小者。需注意集合不能为空,否则抛出NoSuchElementException,使用前应判断集合非空。该方法简洁高效,适用于大多数场景。

在Java中查找集合中的最大值和最小值,最常用的方式是使用 Collections.max() 和 Collections.min() 方法。这两个方法适用于实现了 Collection 接口的类,比如 ArrayList、LinkedList 等。
使用 Collections 工具类
Collections 类提供了静态方法来操作或查询集合。只要集合中的元素实现了 Comparable 接口(如 Integer、String、Double 等),就可以直接使用:
-
Collections.max(collection)返回集合中的最大元素 -
Collections.min(collection)返回集合中的最小元素
示例代码:
import java.util.*; Listnumbers = new ArrayList<>(Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6)); Integer max = Collections.max(numbers); // 结果:9 Integer min = Collections.min(numbers); // 结果:1 System.out.println("最大值:" + max); System.out.println("最小值:" + min);
自定义比较器(Comparator)
如果集合中的对象不是基本类型,或者你想按照特定规则比较,可以传入一个 Comparator。例如,对字符串按长度找最长或最短:
立即学习“Java免费学习笔记(深入)”;
Listwords = Arrays.asList("apple", "hi", "banana", "a"); String longest = Collections.max(words, Comparator.comparing(String::length)); String shortest = Collections.min(words, Comparator.comparing(String::length)); System.out.println("最长的字符串:" + longest); // banana System.out.println("最短的字符串:" + shortest); // a
处理自定义对象
假设有一个 Person 类,想根据年龄找最年长或最年轻的人:
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
List people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
);
Person oldest = Collections.max(people, Comparator.comparing(p -> p.age));
Person youngest = Collections.min(people, Comparator.comparing(p -> p.age));
System.out.println("最年长者:" + oldest.name); // Charlie
System.out.println("最年轻者:" + youngest.name); // Bob
注意事项
这些方法要求集合不为空,否则会抛出 NoSuchElementException。使用前最好判断是否为空:
if (!collection.isEmpty()) {
T max = Collections.max(collection);
}
基本上就这些。对于大多数场景,Collections.max 和 Collections.min 配合 Comparator 能满足需求,简洁且高效。










