Getting indexes of maximum number in array

Viewed 2884

I have an array containing numbers which are ranks.

Something like this :

0 4 2 0 1 0 4 2 0 4 0 2

Here 0 corresponds to the lowest rank and max number corresponds to highest rank. There may be multiple indexes containing highest rank.

I want to find index of all those highest rank in array. I have achieved with following code:

import java.util.*;

class Index{

    public static void main(String[] args){

        int[] data = {0,4,2,0,1,0,4,2,0,4,0,2};
        int max = Arrays.stream(data).max().getAsInt();
        ArrayList<Integer> indexes = new ArrayList<Integer>();

        for(int i=0;i<12;i++){
            if(data[i]==max){
               indexes.add(i);
            }
        }

        for(int j=0;j<indexes.size();j++){
            System.out.print(indexes.get(j)+" ");   
        }
        System.out.println();
    }
}

I have got result as : 1 6 9

Is there any better way than this ?

Because, In my case there may be an array containing millions of elements due to which I have some issue regarding performance.

So,

Any suggestion is appreciated.

3 Answers
Related