如何对List


问题内容

我创建了以下方法:

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

它非常简单,并且在用户区域设置中返回世界国家/地区的列表。然后,我对其进行排序以使其按字母顺序排列。这一切都很好(除了我似乎偶尔会得到国家的重复!)。

无论如何,无论如何,我需要将美国和英国放在列表的顶部。我的问题是我无法隔离将为美国和英国返回的索引或字符串,因为这是特定于语言环境的!

任何想法将不胜感激。


问题答案:

您还可以使用TreeSet来消除重复项,并使用自己来消除ComparatorUS和GB。

由于每个国家/地区通常有多个区域设置,因此您会得到重复(这将消除这种情况)。有一个美国(西班牙)和一个美国(英语),例如三个瑞士(法国,德国和意大利)。

public class AllLocales {
  // Which Locales get priority.
  private static final Locale[] priorityLocales = {
    Locale.US,
    Locale.UK
  };

  private static class MyLocale implements Comparable<MyLocale> {
    // My Locale.
    private final Locale me;

    public MyLocale(Locale me) {
      this.me = me;
    }

    // Convenience
    public String getCountry() {
      return me.getCountry();
    }

    @Override
    public int compareTo(MyLocale it) {
      // No duplicates in the country field.
      if (getCountry().equals(it.getCountry())) {
        return 0;
      }
      // Check for priority ones.
      for (int i = 0; i < priorityLocales.length; i++) {
        Locale priority = priorityLocales[i];
        // I am a priority one.
        if (getCountry().equals(priority.getCountry())) {
          // I come first.
          return -1;
        }
        // It is a priority one.
        if (it.getCountry().equals(priority.getCountry())) {
          // It comes first.
          return 1;
        }
      }
      // Default to straight comparison.
      return getCountry().compareTo(it.getCountry());
    }
  }

  public static List<String> listAll() {
    Set<MyLocale> byLocale = new TreeSet();
    // Gather them all up.
    for (Locale locale : Locale.getAvailableLocales()) {
      final String isoCountry = locale.getDisplayCountry();
      if (isoCountry.length() > 0) {
        //System.out.println(locale.getCountry() + ":" + isoCountry + ":" + locale.getDisplayName());
        byLocale.add(new MyLocale(locale));
      }
    }
    // Roll them out of the set.
    ArrayList<String> list = new ArrayList<>();
    for (MyLocale l : byLocale) {
      list.add(l.getCountry());
    }
    return list;
  }

  public static void main(String[] args) throws InterruptedException {
    // Some demo usages.
    List<String> locales = listAll();
    System.out.println(locales);
  }
}