gpt4 book ai didi

java - 如何对包含字符串数组的数组列表进行排序?

转载 作者:行者123 更新时间:2023-11-30 06:08:57 25 4
gpt4 key购买 nike

List<String[]> allWordList = new ArrayList<>();

我想根据字符串数组中的第一个元素按字母顺序对“allWordList”列表进行排序。

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

Collection.sort();

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

List<String>

而不是

List<String[]>

需要明确的是,我不想对单个 string[] 元素进行排序。我想根据字符串数组的第一个元素对整个列表进行排序。

最佳答案

一个简单的自定义比较器就可以解决问题。

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

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

关于java - 如何对包含字符串数组的数组列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39059094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com