排序几个“链接”列表 [英] 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]
我需要排序的个个按字母顺序根据列表与LT;弦乐>名字
元素。结果
有人能解释我如何做到这一点?
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);
}
和排序,这份名单由名称
,使用自定义比较:
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屋!
查看全文