首页 > 解决方案 > 我如何从 java 中的 ISO3166-1 alpha-2 国家代码中获取国家名称

问题描述

我在 API 的响应中从服务器获取ISO alpha-2 国家代码,但我需要将该ISO alpha-2 国家代码转换为国家名称。我正在使用 Java 8。

标签: java-8appserver

解决方案


使用下面的代码,我们可以从 Java 8 语言环境中获取所有国家的 ISO3 代码和 ISO2 代码以及国家名称。

public static void main(String[] args) throws Exception {   
  String[] isoCountries = Locale.getISOCountries();
    for (String country : isoCountries) {
        Locale locale = new Locale("en", country);
        String iso = locale.getISO3Country();
        String code = locale.getCountry();
        String name = locale.getDisplayCountry();
        System.out.println(iso + " " + code + " " + name);
    }
}

您还可以创建查找表映射以在 ISO 代码之间进行转换。因为我需要在 iso3 和 iso2 之间进行转换,所以根据它创建地图。

String[] isoCountries = Locale.getISOCountries();
    Map<String, String> countriesMapping = new HashMap<String, String>();
    for (String country : isoCountries) {
        Locale locale = new Locale("en", country);
        String iso = locale.getISO3Country();
        String code = locale.getCountry();
        String name = locale.getDisplayCountry();
        countriesMapping.put(iso, code);
    }

推荐阅读