【问题标题】:Sorting a list while keeping a few elements always at the top对列表进行排序,同时保持一些元素始终位于顶部
【发布时间】:2014-01-27 11:58:04
【问题描述】:

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

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

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

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

最有效的方法是什么?

【问题讨论】:

标签: java sorting collections arraylist


【解决方案1】:

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

输出:

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

我起初误读了您的问题(或者它是作为忍者编辑添加的)所以这里是更新版本。

【讨论】:

  • “英国”和“美国”的顺序在该解决方案中是不确定的。另一种方法是从列表中删除重要国家,对其进行排序,然后将列表与重要国家和排序的国家一起加入。
【解决方案2】:

Comparator 中实施该规则。您可以使用Collections.sort()

对您的列表进行排序

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2014-09-05
    • 2012-03-18
    • 1970-01-01
    相关资源
    最近更新 更多