2014-01-09 43 views
2

我们有一个List<Country>它按国家/地区名称排列按countryName排列。排序列表,同时保留几个元素始终在顶部

class Country { 
    int id; 
    String countryCode; 
    String countryName; 
} 

Country是一个实体对象,我们没有访问源(它在被许多应用程序共享一个jar文件)。

现在我想修改列表,使国名“美国”和“英国”排在第一位,列表的其余部分按照相同的字母顺序排列。

什么是最有效的方法来做到这一点?

+0

这将有助于显示列表当前如何排序。 –

+0

http://docs.oracle.com/javase/tutorial/collections/interfaces/order.html –

+0

@Sinto,如果您仍然阅读:取消删除您的帖子。我非常喜欢你的回答,并且正在对它进行双重检查。 –

回答

6

创建自己的comparator结合Collections.Sort(collection, Comparator)。与正常的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); 
    } 
} 

输出:

美利坚合众国
英国
巴林
比利时
芬兰
乐高
墨西哥

我最初误解了你的问题(或者它被添加为忍者编辑),所以这里是更新后的版本。

相关问题