2014-01-09 44 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); 
    } 
} 

輸出:

美利堅合衆國
英國
巴林
比利時
芬蘭
樂高
墨西哥

我最初誤解了你的問題(或者它被添加爲忍者編輯),所以這裏是更新後的版本。

相關問題