我有一个包含国家名称的List<String>对象。我如何按字母顺序对这个列表排序?
当前回答
假设这些是字符串,使用方便的静态方法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));
假设这些是字符串,使用方便的静态方法sort:
Collections.sort(listOfCountryNames)
在一行中,使用Java 8:
list.sort(Comparator.naturalOrder());
使用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)
推荐文章
- 如何在POM.xml中引用环境变量?
- 如何在android中复制一个文件?
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- 将整数转换为字符串,以逗号表示千
- 接口方法的最终参数-有什么意义?
- Java中的@UniqueConstraint注释
- 如何在清洁模式下运行eclipse ?如果我们这样做会发生什么?
- 获取java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory异常
- Java中的正则表达式命名组
- c#和Java的主要区别是什么?
- 什么是NullPointerException,我如何修复它?
- 在Java中使用“final”修饰符
- 无法在Flutter上找到捆绑的Java版本
- 如何在Kotlin解析JSON ?
- 如何在新的材质主题中改变背面箭头的颜色?