java快速寻找一个数组的最大值或最小值, min, max,三种方法
java 中 寻找一个数组中的最大值或最小,除了自己专门编写一个 min 或 max 函数外,还有几种方式方便使用。
使用 stream
将一个数组放进 stream 里面,然后直接调用 stream 里的 min 或 max 函数得到最大值或最小值。
使用 collection
将数组转化为对象数组,即 int 转化为 Integer (需要使用 toObject 转换)。 然后调用 Collection 里面的 min或max.
使用 Arrays 中的 sort
Arrays 类中的 sort 可以自动将一个数组排序,排序后数组中第一个元素就是 最小值,缺点是会改变数组。
————————————————
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import java.util.Arrays; import java.util.Collections; import org.apache.commons.lang3.ArrayUtils; public class HelloWorld { public static void main(String[] args) { // TODO Auto-generated method stub int a[] = { 10 , 5 , 8 }; int min = Arrays.stream(a).min().getAsInt(); System.out.println(min); min = Collections.min(Arrays.asList(ArrayUtils.toObject(a))); System.out.println(min); Arrays.sort(a); System.out.println(a[ 0 ]); } } |
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 分享4款.NET开源、免费、实用的商城系统
· 解决跨域问题的这6种方案,真香!
· 5. Nginx 负载均衡配置案例(附有详细截图说明++)
· Windows 提权-UAC 绕过