国家/地区的ISO2国家/地区代码

国家/地区的ISO2国家/地区代码

问题描述:

在Java中是否有一种简单的方法可以从给定的国家/地区名称中获取ISO2代码,例如CH在给定瑞士时?

Is there an easy way in Java to get the ISO2 code from a given country name, for example "CH" when given "Switzerland"?

唯一的解决方案我现在可以想到的是将所有国家代码和名称保存在一个数组中并迭代它。任何其他(更简单)的解决方案?

The only solution I can think of at the moment is to save all the country codes and names in an array and iterate over it. Any other (easier) solutions?

您可以使用内置的区域设置 class:

You could use the built-in Locale class:

Locale l = new Locale("", "CH");
System.out.println(l.getDisplayCountry());

打印瑞士。请注意,我没有提供语言。

prints "Switzerland" for example. Note that I have not provided a language.

因此,您可以为反向查找做的是从可用国家/地区构建地图:

So what you can do for the reverse lookup is build a map from the available countries:

public static void main(String[] args) throws InterruptedException {
    Map<String, String> countries = new HashMap<>();
    for (String iso : Locale.getISOCountries()) {
        Locale l = new Locale("", iso);
        countries.put(l.getDisplayCountry(), iso);
    }

    System.out.println(countries.get("Switzerland"));
    System.out.println(countries.get("Andorra"));
    System.out.println(countries.get("Japan"));
}