Search code examples
javaarraysarraylistintellij-ideaalphabetical

Finding the string that is first in alphabetical order in an ArrayList of Strings


I have an ArrayList of notes in the form of strings (an example of one would be "take out the trash". I have a notes class and one of the methods is supposed to go through the notes stored in the ArrayList and find the one that comes first in the alphabet. This is my current method:

public String firstAlphabetically() {
        String min = "";
        for (int i = 0; i < notes.size(); i++) {
            for (int j = i + 1; j < notes.size() + 1; i++) {
                if ((notes.get(i)).compareTo(notes.get(j)) < 0) {
                    min = notes.get(i);
                } else {
                    min = notes.get(j);
                }
            }
        }
        return min;
    }

However, when I run the program, I get an out of bounds error on this line: for (int j = i + 1; j < notes.size() + 1; i++). I know what an out of bounds error is but I can't figure out what part of that line would cause the program to crash. Could anybody tell me what I am doing wrong?


Solution

  • Problem 1:
    The loop termination condition should be i < notes.size()

    Problem 2:
    Too much code. Try this 1-liner instead:

    return notes.stream().sorted().findFirst().orElse(null);