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


当前回答

您可以使用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);

其他回答

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

Collections.sort(listOfCountryNames)

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

下行字母:

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

在一行中,使用Java 8:

list.sort(Comparator.naturalOrder());

这是你要找的东西

listOfCountryNames.sort(String::compareToIgnoreCase)