我们有一个List<Country>
其中包含按字母顺序排序的国家/地区列表countryName
.
class Country {
int id;
String countryCode;
String countryName;
}
Country
是一个实体对象,我们无权访问源(它位于许多应用程序共享的 jar 文件中)。
现在我想修改列表,使国家名称“美利坚合众国”和“英国”排在前面,列表的其余部分按相同的字母顺序排列。
最有效的方法是什么?
创建您自己的比较器 http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html结合Collections.Sort(collection, Comparator) http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29。这与正常的方式不同Comparator
是您必须明确优先选择您始终希望位于顶部的条目。
public class Main {
public static void main(String[] args) {
new Main();
}
public Main(){
List<Country> list = new ArrayList<>();
list.add(new Country("Belgium"));
list.add(new Country("United Kingdom"));
list.add(new Country("Legoland"));
list.add(new Country("Bahrain"));
list.add(new Country("United States of America"));
list.add(new Country("Mexico"));
list.add(new Country("Finland"));
Collections.sort(list, new MyComparator());
for(Country c : list){
System.out.println(c.countryName);
}
}
}
class Country {
public Country(String name){
countryName = name;
}
int id;
String countryCode;
String countryName;
}
class MyComparator implements Comparator<Country> {
private static List<String> important = Arrays.asList("United Kingdom", "United States of America");
@Override
public int compare(Country arg0, Country arg1) {
if(important.contains(arg0.countryName)) { return -1; }
if(important.contains(arg1.countryName)) { return 1; }
return arg0.countryName.compareTo(arg1.countryName);
}
}
Output:
美国
英国
巴林
比利时
芬兰
乐高乐园
墨西哥
我一开始误读了你的问题(或者它是作为忍者编辑添加的),所以这是更新的版本。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)