1. 使用 stream
将一个数组放进 stream 里面,然后直接调用 stream 里的 min 或 max 函数得到最大值。
@Test
public void index2(){
int ages[] = {18 ,23 ,21 ,19 ,25 ,29 ,17};
int maxNum = Arrays.stream(ages).max().getAsInt();
System.out.println("最大值为:"+ maxNum);
}
2. 使用 collection
将数组转化为对象数组,即 int 转化为 Integer (需要使用数组转换)。 然后调用 Collection 里面的 min或max.
@Test
public void index3(){
int ages[] = {18 ,23 ,21 ,19 ,25 ,29 ,17};
Integer newAges[] = new Integer[ages.length];
for(int i=0;i<ages.length;i++) {
newAges[i] = (Integer)ages[i];
}
int maxNum = Collections.max(Arrays.asList(newAges));
System.out.println("最大值为:"+ maxNum);
}
3. 使用 Arrays 中的 sort
Arrays 类中的 sort 可以自动将一个数组排序,排序后数组中最后一个元素就是 最大值,缺点是会改变数组。
@Test
public void index1(){
int ages[] = {18 ,23 ,21 ,19 ,25 ,29 ,17};
Arrays.sort(ages);
int maxNum = ages[ages.length-1];
System.out.println("最大值为:"+ maxNum);
}
4.使用自定义函数
默认把第一个元素作为最大值,然后for循环,如果大于最大值,则进行替换。
public int getMaxAge()
{
int ages[] = {18 ,23 ,21 ,19 ,25 ,29 ,17};
int max = ages[0];
for(int i = 1;i<ages.length;i++){
if(ages[i]>max){
max = ages[i];
}
}
return max;
}
来源:oschina
链接:https://my.oschina.net/u/4284954/blog/4307900