在字符串的 ArrayList 中查找按字母顺序排在首位的字符串

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

我有一个字符串形式的笔记 ArrayList(一个例子是 "take out the trash"。我有一个笔记 class,其中一种方法应该通过笔记存储在 ArrayList 中并找到字母表中第一个出现的那个。这是我目前的方法:

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;
    }

然而,当我 运行 程序时,我在这一行得到一个越界错误:for (int j = i + 1; j < notes.size() + 1; i++)。我知道什么是越界错误,但我不知道该行的哪一部分会导致程序崩溃。谁能告诉我我做错了什么?

添加:

implements Comparable<Note>

添加到您的 class 签名,然后在您的笔记 class 中实现 compareTo() 方法。然后你可以使用:

Collections.sort(listOfNotes)

问题 1:
循环终止条件应该是i < notes.size()

问题 2:
代码太多。试试这个 1-liner:

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