Is there a faster way to check for the largest value(int or double) in an array?

Viewed 33

The following code compiles just fine, I just wanted to know if I could do everything in a much shorter form. Pardon me if i'm overlooking something really simple. Also I used a.length-a.length instead of 0 because I'm doing this to show that I know WHY this or that for 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);
    }
}
1 Answers

tl;dr

if I could do everything in a much shorter form

Shorter? Let a stream do the work. It’s a one-liner.

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

See this code run at Ideone.com.

8

Details

Call Arrays.stream to make a stream of an array’s elements, an IntStream. Call IntStream#max to get the biggest value.

The result is an OptionalInt, optional because if your array were empty there would be no int value to return. The OptionalInt#getAsInt method returns a value if present, otherwise throws NoSuchElementException.

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

8

Related