Collections.min和max用于获取集合极值,支持Comparable对象或自定义Comparator;示例中求数值最小最大值、字符串最长最短及Person按年龄取极值,需注意集合非空、元素可比较,性能O(n),多值并列时返回首个。

在Java中,Collections.min 和 Collections.max 是获取集合最小值和最大值的便捷方法。它们定义在 java.util.Collections 工具类中,适用于任何实现 Collection 接口的集合类型,如 ArrayList、LinkedList、HashSet 等。
对于存储实现了 Comparable 接口的元素(如 Integer、String)的集合,可以直接调用 min 或 max 方法。
Collections.min(collection) 获取最小值Collections.max(collection) 获取最大值示例:
List<Integer> numbers = Arrays.asList(5, 2, 8, 1, 9); int min = Collections.min(numbers); // 结果为 1 int max = Collections.max(numbers); // 结果为 9
当集合中的对象不具备自然排序,或你想按特定规则比较时,可以传入一个 Comparator 实现。
立即学习“Java免费学习笔记(深入)”;
示例:找出最长的字符串
List<String> words = Arrays.asList("hi", "hello", "world", "Java");
String shortest = Collections.min(words, Comparator.comparing(String::length));
String longest = Collections.max(words, Comparator.comparing(String::length));
// shortest = "hi", longest = "hello" 或 "world"(长度相同)
假设有一个 Person 类,包含姓名和年龄,想找出年龄最小或最大的人。
class Person {
String name;
int age;
// 构造方法、getter等省略
}
使用 Comparator 按年龄比较:
List<Person> people = Arrays.asList(
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
);
Person youngest = Collections.min(people, Comparator.comparing(p -> p.age));
Person oldest = Collections.max(people, Comparator.comparing(p -> p.age));
使用这两个方法时需注意以下几点:
NoSuchElementException
Comparable,要么提供 Comparator
基本上就这些。掌握 Collections.min 和 max 能快速完成极值查询,结合 Comparator 更是灵活强大。不复杂但容易忽略细节,比如空集合判断,建议使用前先检查 collection.isEmpty()。
以上就是Java里如何使用Collections.min和Collections.max获取集合极值_集合极值操作技巧解析的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号