java - 如何重新排序列表<String>

标签 java list locale

我创建了以下方法:

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/

相关文章:

java - 初始化子类中不同类型的 'final' 字段

java - 如何获取任意整数数组并返回具有相同整数但不重复的数组

sharepoint - 是否可以从 Excel 工作表填充 SharePoint 列表?

Java - NumberValue 到没有货币符号的字符串

java - 显示具有 AppCompat 主题的壁纸 (Android)

java - 如何创建父项目的 Spring Boot 项目子模块

list - LISP:力评估

c# - LINQ 等效查询

facebook - Locale=nl_BE (Dutch Belgium) 不再受支持(在像按钮这样的 iframe 中)?

c++ - 在Linux中存储语言环境名称的缓冲区的大小应该是多少?