0

I'm writing a program to count how many times each unique word appears in a text file, then return the word that occurred the most times along with how many times it occurred. Because I don't know how many different words there will be I cannot use an array since I can't predict how big it will need to be. Therefore I used two parallel ArrayLists. myWords is a list of strings and myFreqs is a list of ints, such that each index in myFreqs contains the number of occurrences of the word stored in the same index of myWords.

To do this I am trying to write a for loop that identifies the index in myFreqs which contains the highest value. I am struggling to write this loop though because ArrayList has no .length() method so I'm not sure the best way to write the stop condition in the loop. I have tried converting the ArrayList to an Array using

        myFreqs.toArray(<Integer> array);

so that I can get the length of the array but this is giving me compile-time errors. I have tried several slightly different versions of the above and I get either "illegal start of expression" errors or “A Non-static method cannot be referenced from a static context” errors. I am getting the feeling that there is a much simpler and more direct way to achieve what I want that I am overlooking.

private ArrayList<String> myWords;
private ArrayList<Integer> myFreqs;

public int findIndexOfMax () {
    int[] array = new Array[100];
    myFreqs.toArray(<Integer> array);
    int maxVal = 0;
    int maxIdx = -1;
    for (int k = 0; k < array.length; k++) {
        if (array[k] > maxVal) {
            maxVal = array[k];
            maxIdx = k;
        }
    }
    return maxIdx;
}
Nigel Wilson
  • 17
  • 1
  • 1
  • 11

2 Answers2

1

You can use Java Streams to get the index of the max value:

int index = IntStream.range(0, myFreqs.size()).boxed()
        .max(Comparator.comparingInt(myFreqs::get))
        .orElse(-1);
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
1

Samuel Philipp's answer is excellent, however, you don't need to convert into array to get List's length. Instead of converting ArrayList into array int[], use List.size() method in order to get number of elements in the list.

Dzmitry Bahdanovich
  • 1,735
  • 2
  • 17
  • 34