如何对包含字符串数组的arraylist进行排序?

viv*_*rma 2 java sorting arraylist

List<String[]> allWordList = new ArrayList<>();
Run Code Online (Sandbox Code Playgroud)

我想按字母顺序基于字符串数组中的第一个元素对"allWordList"列表进行排序.

我有一个包含大小为2的字符串数组的列表.所以基本上我想通过比较字符串数组的第一个元素来排序这个列表.

Collection.sort();
Run Code Online (Sandbox Code Playgroud)

不起作用,因为它用于排序......

List<String>
Run Code Online (Sandbox Code Playgroud)

并不是

List<String[]>
Run Code Online (Sandbox Code Playgroud)

要清楚我不想对单个string []元素进行排序.我想根据字符串数组的第一个元素对整个列表进行排序.

das*_*ght 6

一个简单的自定义比较器应该可以做到.

唯一棘手的事情是确保你没有索引到一个空数组:

Collections.sort(allWordList, new Comparator<String[]>() {
    public int compare(String[] o1, String[] o2) {
        if (o1.length == 0) {
            return o2.length == 0 ? 0 : -1;
        }
        if (o2.length == 0) {
            return 1;
        }
        return o2[0].compareTo(o1[0]);
    }
});
Run Code Online (Sandbox Code Playgroud)