我创建了以下方法:
public List<String> listAll() {
List worldCountriesByLocal = new ArrayList();
for (Locale locale : Locale.getAvailableLocales()) {
final String isoCountry = locale.getDisplayCountry();
if (isoCountry.length() > 0) {
worldCountriesByLocal.add(isoCountry);
Collections.sort(worldCountriesByLocal);
}
}
return worldCountriesByLocal;
}
它非常简单,它返回用户区域设置中的世界国家/地区列表。然后我对其进行排序以使其按字母顺序排列。这一切都很完美(除了我似乎偶尔会得到国家/地区的重复项!)。
无论如何,我需要的是将美国和英国放在列表的顶部。我遇到的问题是,我无法隔离将为美国和英国返回的索引或字符串,因为这是特定于区域设置的!
任何想法将不胜感激。
最佳答案
Anyway, what I need is to place the US, and UK at the top of the list regardless. The problem I have is that I can't isolate the index or the string that will be returned for the US and UK because that is specific to the locale!
听起来你应该实现自己的 Comparator<Locale>
通过以下步骤比较两个区域设置:
- 如果区域设置相同,则返回 0
- 如果一个地区是美国,则“获胜”
- 如果一个地区是英国,则“获胜”
- 否则,请使用
o1.getDisplayCountry().compareTo(o2.getDisplayCountry())
(即委托(delegate)现有行为)
(这将使美国排在英国之前。)
然后调用 Collections.sort
使用您的自定义比较器的实例。
在提取国家/地区名称之前执行所有这些操作 - 然后从排序列表中提取它们。
关于java - 如何重新排序列表<String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12747919/