我有一个包含国家名称的List<String>对象。我如何按字母顺序对这个列表排序?


当前回答

使用Collections.sort的两个参数。你会想要一个合适的比较器,处理大小写适当(即词法,而不是UTF16排序),比如通过java.text.Collator.getInstance获得。

其他回答

假设这些是字符串,使用方便的静态方法sort:

Collections.sort(listOfCountryNames)

通过使用Collections.sort(),我们可以对列表进行排序。

public class EmployeeList {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        List<String> empNames= new ArrayList<String>();

        empNames.add("sudheer");
        empNames.add("kumar");
        empNames.add("surendra");
        empNames.add("kb");

        if(!empNames.isEmpty()){

            for(String emp:empNames){

                System.out.println(emp);
            }

            Collections.sort(empNames);

            System.out.println(empNames);
        }
    }
}

输出:

sudheer
kumar
surendra
kb
[kb, kumar, sudheer, surendra]

下行字母:

List<String> list;
...
Collections.sort(list);
Collections.reverse(list);

使用Collections.sort解决方案

如果您被迫使用该List,或者如果您的程序具有类似的结构

创建列表 添加一些国家名称 对它们排序一次 不要再更改这个列表

那么这个答案将是最好的方法。如果你结合Tom Hawtin - tackline的建议,你会得到:

java.util.Collections.sort(listOfCountryNames, Collator.getInstance());

树集的解决方案

如果您可以自由决定,并且您的应用程序可能变得更加复杂,那么您可以更改代码以使用TreeSet。这种集合在插入条目时对它们进行排序。不需要调用sort()。

Collection<String> countryNames = 
    new TreeSet<String>(Collator.getInstance());
countryNames.add("UK");
countryNames.add("Germany");
countryNames.add("Australia");
// Tada... sorted.

旁注为什么我更喜欢树集

这有一些微妙但重要的优势:

It's simply shorter. Only one line shorter, though. Never worry about is this list really sorted right now becaude a TreeSet is always sorted, no matter what you do. You cannot have duplicate entries. Depending on your situation this may be a pro or a con. If you need duplicates, stick to your List. An experienced programmer looks at TreeSet<String> countyNames and instantly knows: this is a sorted collection of Strings without duplicates, and I can be sure that this is true at every moment. So much information in a short declaration. Real performance win in some cases. If you use a List, and insert values very often, and the list may be read between those insertions, then you have to sort the list after every insertion. The set does the same, but does it much faster.

为正确的任务使用正确的集合是编写简短且没有错误的代码的关键。在这种情况下,它不是指示性的,因为你只保存了一行。但是我已经不再计算当有人想要确保没有重复时使用List的频率,然后他们自己构建该功能。或者更糟糕的是,在真正需要Map时使用两个list。

不要误解我的意思:使用集合。排序不是错误或缺陷。但是在很多情况下,TreeSet要干净得多。

这是你要找的东西

listOfCountryNames.sort(String::compareToIgnoreCase)