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


当前回答

在一行中,使用Java 8:

list.sort(Comparator.naturalOrder());

其他回答

下行字母:

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

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

Collections.sort(listOfCountryNames)

你可以使用下面这行

集合。排序(listOfCountryNames String.CASE_INSENSITIVE_ORDER)

它类似于Thilo的建议,但不会区分大小写字符。

JAVA 8相同:-

//Assecnding order
        listOfCountryNames.stream().sorted().forEach((x) -> System.out.println(x));

//Decending order
        listOfCountryNames.stream().sorted((o1, o2) -> o2.compareTo(o1)).forEach((x) -> System.out.println(x));

您可以使用Java 8 Stream或Guava创建一个新的排序副本:

// Java 8 version
List<String> sortedNames = names.stream().sorted().collect(Collectors.toList());
// Guava version
List<String> sortedNames = Ordering.natural().sortedCopy(names); 

另一种选择是通过Collections API就地排序:

Collections.sort(names);