对列表进行排序,同时保持一些元素始终位于顶部

use*_*434 3 java sorting collections arraylist

我们有一个List<Country>按字母顺序排列的国家/地区列表countryName.

 class Country {
   int id;
   String countryCode;
   String countryName;
 }
Run Code Online (Sandbox Code Playgroud)

Country 是一个实体对象,我们无权访问源(它位于许多应用程序共享的jar文件中).

现在我想修改列表,使国家名称"美国"和"英国"排在第一位,列表的其余部分按字母顺序排列.

最有效的方法是什么?

Jer*_*vel 10

结合使用创建自己的比较器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);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

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

我一开始就误读了你的问题(或者它被添加为忍者编辑)所以这里是更新版本.