charlie
charlie

Reputation: 187

How to return first max value in a Java ArrayList

I'm trying to return the first index of the max value of an ArrayList<Integer>. The code below finds the second maximum instead of the first. How do I return the first max value encountered by the loop?

public int findIndexOfMax() {
    int maxIndex = 0;
    for (int k = 0; k < myFreqs.size(); k++) {
        if (myFreqs.get(k) > maxIndex) {
            maxIndex = myFreqs.get(k);
        }
    }
    return maxIndex;
}

What gets returned is 'test. 3'. But it should be the first max which is 3 for the letter 'a'.

Number of unique words: 7
1   this
1   is
3   a
3   test.
1   yes
1   test
1   of
The word that occurs most often and its count are: test. 3

Upvotes: 0

Views: 581

Answers (3)

Tia
Tia

Reputation: 1

since there is a tie between "a" and "test." Frequencies, you want to return the first value which is "a" with the occurrence of 3

to do so, you need to find the max value and its position in myFreqs and then get the value of the other ArrayList containing the words at the index of the position of the max value.

int maxElement = 0;
int maxPosition = 0;
for(int i = 0; i < this.myFreqs.size(); i++){
    if(this.freqs.get(i) > maxElement){
        maxElement = this.freqs.get(i);
        maxPosition = i;
    }
}
return maxPosition;

now you can simply find the first most frequent word in the arrayList of the words:

words.get(maxFreq)

Upvotes: 0

Rahul Rana
Rahul Rana

Reputation: 1

I think you are using the integers on the left as index for the Strings on the right and when you use 3 as index for the second time it is overlapping the value "a" with "test".

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201439

You seem to have forgotten to access the element at the maxIndex in your comparison. And you set the index to the value of the element in your if (instead of the index). I think you wanted,

public int findIndexOfMax() {
    int maxIndex = 0;
    for (int k = 1; k < myFreqs.size(); k++) {
        if (myFreqs.get(k) > myFreqs.get(maxIndex)) {
            maxIndex = k;
        }
    }
    return maxIndex;
}

Upvotes: 3

Related Questions