如何对包含字符串数组的arraylist进行排序?
List<String[]> allWordList = new ArrayList<>();
我想基于字符串数组中的第一个元素按字母顺序对"allWordList"列表进行排序.
I would like to sort the "allWordList" list based on the first element in string array alphabetically.
我有一个包含大小为2的字符串数组的列表.因此,基本上,我想通过比较字符串数组的第一个元素对该列表进行排序.
I have a list that contains string array which are of size 2. So basically i want to sort this list by comparing the first element of the string array.
Collection.sort();
由于用于排序而无法工作...
does not work as it is used to sort......
List<String>
而不是
List<String[]>
要清楚,我不想对单个string []元素进行排序.我想根据字符串数组的第一个元素对整个列表进行排序.
to be clear i do not want to sort the individual string[] elements. I would like to sort the entire list based on the very first element of the string array.
一个简单的自定义比较器应该可以解决问题.
A simple custom comparator should do the trick.
唯一棘手的事情是确保您没有索引到空数组中
The only tricky thing is making sure that you are not indexing into an empty array:
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]);
}
});