我有3个列表,因此其元素的顺序很重要:
names: [a, b, c, d]
files: [a-file, b-file, c-file, d-file]
counts: [a-count, b-count, c-count, d-count]
我需要根据List<String> names
元素按字母顺序对所有进行排序。
有人能解释我怎么做吗?
答案 0 :(得分:5)
创建一个类来保存元组:
class NameFileCount {
String name;
File file;
int count;
public NameFileCount(String name, File file, int count) {
...
}
}
然后将三个列表中的数据分组到此类的单个列表中:
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);
}
使用自定义比较器按name
对此列表进行排序:
Collections.sort(nfcs, new Comparator<NameFileCount>() {
public int compare(NameFileCount x, NameFileCount y) {
return x.name.compareTo(y.name);
}
});
(为简洁起见,省略了属性访问器,空检查等。)