对几个“链接"列表进行排序 [英] Sort several 'linked' Lists
本文介绍了对几个“链接"列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 3 个列表,因此它们元素的顺序很重要:
I have 3 lists so the order of their elements is important:
names: [a, b, c, d]
files: [a-file, b-file, c-file, d-file]
counts: [a-count, b-count, c-count, d-count]
我需要根据List
元素.
有人能解释一下怎么做吗?
I need to sort all of them alphabetically based on the List<String> names
elements.
Can someone explain me how to do this?
推荐答案
创建一个类来保存元组:
Create a class to hold the tuple:
class NameFileCount {
String name;
File file;
int count;
public NameFileCount(String name, File file, int count) {
...
}
}
然后将三个列表中的数据分组到此类的单个列表中:
Then group the data from the three lists into a single list of this class:
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
对该列表进行排序:
And sort this list by name
, using a custom comparator:
Collections.sort(nfcs, new Comparator<NameFileCount>() {
public int compare(NameFileCount x, NameFileCount y) {
return x.name.compareTo(y.name);
}
});
(为简洁起见,省略了属性访问器、空检查等.)
(Property accessors, null checking, etc omitted for brevity.)
这篇关于对几个“链接"列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文