问题
I have a sample class, say Country
:
class Country {
public String name;
public int population;
public Flag flag;
...
}
I have this Flag
class defined somewhere else
class Flag {
String id;
int pixel;
...
}
Now I create a separate comparator DefaultFlagRankingComparator() that can sort Flag by id. How can I sort a list of Country by Flag id, using this DefaultFlagRankingComparator()?
回答1:
You can invoke the compare method of the Comparator
with the flag field of each country.
DefaultFlagRankingComparator flagComparator =
new DefaultFlagRankingComparator();
Collections.sort(countries, (a, b) ->
flagComparator.compare(a.getFlag(), b.getFlag()));
You could also use Comparator.comparing to create a Comparator
using a key extracting function and a Comparator
that compares those keys (as suggested by Louis Wasserman).
DefaultFlagRankingComparator flagComparator =
new DefaultFlagRankingComparator();
Collections.sort(countries,
Comparator.comparing(Country::getFlag, flagComparator));
回答2:
You can compare
String
values of ids using predefined methods:Arrays.sort(countries, (c1, c2) -> Objects.compare( c1.getFlag().getId(), c2.getFlag().getId(), Comparator.naturalOrder()));
Arrays.sort(countries, Comparator.comparing(country -> country.getFlag().getId(), Comparator.naturalOrder()));
You can specify a custom Comparator:
Arrays.sort(countries, Comparator .comparing(country -> country.getFlag(), new DefaultFlagRankingComparator()));
static class DefaultFlagRankingComparator implements Comparator<Flag> { @Override public int compare(Flag o1, Flag o2) { return Objects.compare(o1.getId(), o2.getId(), Comparator.naturalOrder()); } }
You can implement interface Comparable in the
Flag
class:Arrays.sort(countries, Comparator.comparing(Country::getFlag));
static class Flag implements Comparable<Flag> { String id; public String getId() { return id; } @Override public int compareTo(Flag that) { return Objects.compare(this.getId(), that.getId(), Comparator.naturalOrder()); } }
来源:https://stackoverflow.com/questions/65485183/how-to-sort-by-a-field-of-class-with-its-own-comparator