List<String[]> allWordList = new ArrayList<>();
I would like to sort the "allWordList" list based on the first element in string array alphabetically.
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>
and not
List<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]);
}
});
您可以提供自己的比较器,例如作为lambda表达式:
allWordList.sort((o1, o2) -> o1[0].compareTo(o2[0]));
I'd go with a variation of @dasblinkenlight 's answer where I'd don't think comparing array length's is correct behavior.
private void sort() {
List<String[]> allWordList = new ArrayList<String[]>();
// fill the list...
Collections.sort(allWordList, new FirstElementComparator());
// and so on...
}
private static class FirstElementComparator implements Comparator<String[]>
{
@Override
public int compare(String[] sa1, String[] sa2) {
String str1 = sa1[0];
String str2 = sa2[0];
int result = 0;
if (str1 == null) {
result = (str2 == null) ? 0 : -1;
}
else {
result = str1.compareTo(str2);
}
return result;
}
}
You don't need to write your own Comparator
:
allWordList
.stream()
.sorted(Comparator.comparing(a -> a[0], String.CASE_INSENSITIVE_ORDER))
.collect(Collectors.toList());
You can omit the String.CASE_INSENSITIVE_ORDER
if the ordering should be case-sensitive.
Or if you need locale-dependent ordering, take a look at Collator
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.