son*_*ain 0 java sorting list arraylist
我有3个列表,所以它们的元素顺序很重要:
names: [a, b, c, d]
files: [a-file, b-file, c-file, d-file]
counts: [a-count, b-count, c-count, d-count]
Run Code Online (Sandbox Code Playgroud)
我需要根据元素按字母顺序对它们进行排序List<String> names.
有人能解释我怎么做吗?
创建一个类来保存元组:
class NameFileCount {
String name;
File file;
int count;
public NameFileCount(String name, File file, int count) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
然后将三个列表中的数据分组到此类的单个列表中:
List<NameFileCount> nfcs = new ArrayList<>();
for (int i = 0; i < names.size(); i++) {
NameFileCount nfc = new NameFileCount(
names.get(i),
files.get(i),
counts.get(i)
);
nfcs.add(nfc);
}
Run Code Online (Sandbox Code Playgroud)
并name使用自定义比较器对此列表进行排序:
Collections.sort(nfcs, new Comparator<NameFileCount>() {
public int compare(NameFileCount x, NameFileCount y) {
return x.name.compareTo(y.name);
}
});
Run Code Online (Sandbox Code Playgroud)
(为简洁起见,省略了属性访问器,空检查等.)
| 归档时间: |
|
| 查看次数: |
128 次 |
| 最近记录: |