对列表进行排序,同时将一些元素始终放在顶部 [英] Sorting a list while keeping a few elements always at the top

查看:27
本文介绍了对列表进行排序,同时将一些元素始终放在顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个 List,其中包含按字母顺序按 countryName 排序的国家/地区列表.

We have a List<Country> which holds the list of countries in alphabetical order sorted by the countryName.

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

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

Country is an entity object and we don't have access to the source (it's in a jar file that is shared by many applications).

现在我想修改列表,使国家名称美利坚合众国"和英国"排在最前面,列表的其余部分按相同的字母顺序排列.

Now I want to modify the list in such a way that country names 'United States of America' and 'United Kingdom' comes first and the rest of the list is in the same alphabetical order.

最有效的方法是什么?

推荐答案

创建您自己的 比较器 结合 Collections.Sort(collection, Comparator).这与普通 Comparator 的不同之处在于,您必须明确地优先考虑您总是想要的条目.

Create your own comparator in combination with Collections.Sort(collection, Comparator). The way this differs from a normal Comparator is that you have to explicitly give preference to the entries that you always want on top.

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);
    }
}

输出:

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

United States of America
United Kingdom
Bahrain
Belgium
Finland
Legoland
Mexico

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

I misread your question at first (or it was added as a ninja edit) so here's the updated version.

这篇关于对列表进行排序,同时将一些元素始终放在顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆