排序列表,而在顶部保持几个元件总是 [英] Sorting a list while keeping a few elements always at the top

查看:81
本文介绍了排序列表,而在顶部保持几个元件总是的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个列表<国家> 持有由国家名称排序国家的字母顺序列表中。

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

国家是一个实体对象,我们没有访问源代码(这是在由许多应用程序共享一个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.

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

What is the most efficient way to do this ?

推荐答案

创建自己的结合比较与<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29\"相对=nofollow> Col​​lections.Sort(收集,比较器) 。该办法从这个普通的比较不同的是,你必须明确给出preference到你总是希望在上面的条目。

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天全站免登陆