简体   繁体   English

排序几个“链接”列表

[英]Sort several 'linked' Lists

I have 3 lists so the order of their elements is important: 我有3个列表,因此它们的元素顺序很重要:

names: [a, b, c, d]
files: [a-file, b-file, c-file, d-file]
counts: [a-count, b-count, c-count, d-count]

I need to sort all of them alphabetically based on the List<String> names elements. 我需要根据List<String> names元素按字母顺序对它们进行排序。
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: 然后使用自定义比较器按name对列表进行排序:

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.) (为简便起见,省略了属性访问器,空检查等。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM