有没有一种更快的方法来检查数组中的最大值(int或double)



下面的代码编译得很好,我只是想知道我是否可以用更短的形式完成所有事情。如果我忽略了一些非常简单的东西,请原谅。此外,我使用了a.length-a.length而不是0,因为我这样做是为了表明我知道APCSA为什么这样或那样。

public class main
{
public static void main(String[] args) //Goal is to make a quick program that finds the largest value in an array.
{
int a[] = new int[]{2,2,3,4,5,6,6,2,8}; //Arbitrary Values
int lnum = 0;
for(int i = a.length-a.length; i < a.length; i++){ // Used a.length-a.length instead of 0
if (i==a.length-a.length){ // Used a.length-a.length instead of 0
lnum = a[i];
}
else if(a[i]>lnum && a[i]>a[i-1]){
lnum = a[i];
}
}
System.out.println(lnum);
}
}

tl;dr

如果我可以用更短的格式完成所有工作

更短?让溪流来做这项工作。这是一句俏皮话。

Arrays
.stream( new int[] { 2 , 2 , 3 , 4 , 5 , 6 , 6 , 2 , 8 } )
.max()
.getAsInt()

请在Ideone.com.上查看此代码

8

详细信息

调用Arrays.stream以生成一个数组元素流,即IntStream。调用IntStream#max以获得最大值。

结果是一个OptionalInt,这是可选的,因为如果数组为空,就不会返回int值。OptionalInt#getAsInt方法返回一个值(如果存在(,否则抛出NoSuchElementException

int[] a = new int[] { 2 , 2 , 3 , 4 , 5 , 6 , 6 , 2 , 8 }; 
int max = Arrays.stream( a ).max().getAsInt();  

8

最新更新