基础比较:两个数求最大值
使用条件运算符或Math.max()
方法:
int a = 10, b = 20; // 方法1:条件运算符 int max = (a > b) ? a : b; // 方法2:Math.max()方法 int max = Math.max(a, b); System.out.println("最大值: " + max); // 输出20
数组求最大值
循环遍历法(通用性强)
int[] arr = {5, 8, 2, 10, 3}; int max = arr[0]; // 初始化为第一个元素 for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } } System.out.println("数组最大值: " + max); // 输出10
使用Arrays.sort()排序
import java.util.Arrays; int[] arr = {5, 8, 2, 10, 3}; Arrays.sort(arr); // 升序排序 int max = arr[arr.length - 1]; // 取最后一个元素 System.out.println("数组最大值: " + max); // 输出10
使用Stream API(Java 8+)
import java.util.Arrays; int[] arr = {5, 8, 2, 10, 3}; int max = Arrays.stream(arr).max().getAsInt(); System.out.println("数组最大值: " + max); // 输出10
集合求最大值(如List)
Collections.max()方法
import java.util.Collections; import java.util.ArrayList; import java.util.List; List<Integer> list = new ArrayList<>(); list.add(5); list.add(8); list.add(2); list.add(10); list.add(3); int max = Collections.max(list); System.out.println("集合最大值: " + max); // 输出10
Stream API(Java 8+)
int max = list.stream().mapToInt(Integer::intValue).max().getAsInt();
三个数求最大值
嵌套使用Math.max()
或条件判断:
int a = 10, b = 20, c = 15; // 方法1:嵌套Math.max() int max = Math.max(a, Math.max(b, c)); // 方法2:条件运算符 int max = (a > b) ? (a > c ? a : c) : (b > c ? b : c); System.out.println("最大值: " + max); // 输出20
注意事项
- 空数组/集合处理:
使用Stream或Collections.max()
时需检查空值:// 避免NoSuchElementException if (arr.length > 0) { int max = Arrays.stream(arr).max().getAsInt(); }
- 性能考量:
- 小规模数据:循环遍历或
Math.max()
效率高。 - 大规模数据:Stream API并行处理更优(
.parallel()
)。
- 小规模数据:循环遍历或
- 特殊类型:
- 浮点数:需考虑精度问题(如
Math.max
支持double
/float
)。 - 负数:上述方法均兼容负数比较。
- 浮点数:需考虑精度问题(如
代码示例总结
场景 | 推荐方法 | 示例代码片段 |
---|---|---|
两个数比较 | Math.max() |
Math.max(a, b) |
数组求最大值 | 循环遍历或Stream API | for循环 或 Arrays.stream(arr).max() |
集合求最大值 | Collections.max() |
Collections.max(list) |
三个数比较 | 嵌套Math.max() |
Math.max(a, Math.max(b, c)) |
引用说明:
本文代码基于Java 17语法编写,Math.max()
方法参考Oracle官方文档,Collections.max()
方法参考Java Collections Framework规范,Stream API部分遵循Java 8+函数式编程规范。
原创文章,发布者:酷盾叔,转转请注明出处:https://www.kd.cn/ask/21689.html