问题描述
我有一个示例课程,例如 Country
:
I have a sample class, say Country
:
class Country {
public String name;
public int population;
public Flag flag;
...
}
我在其他地方定义了这个 Flag
类
I have this Flag
class defined somewhere else
class Flag {
String id;
int pixel;
...
}
现在,我创建一个单独的比较器DefaultFlagRankingComparator(),可以按ID对Flag进行排序.如何使用此DefaultFlagRankingComparator()按标记ID对国家/地区列表进行排序?
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()?
推荐答案
您可以使用每个国家/地区的标志字段调用 Comparator
的compare方法.
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()));
您还可以使用 Comparator.comparing
使用键提取功能和 Comparator 创建
Comparator
比较这些密钥的代码(如 Louis Wasserman 所建议).
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));
这篇关于如何使用自己的比较器按类字段排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!