Reputation: 312
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]
I need to sort all of them alphabetically based on the List<String> names
elements.
Can someone explain me how to do this?
Upvotes: 0
Views: 141
Reputation: 39950
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.)
Upvotes: 5