国家/地区的ISO2国家/地区代码 [英] ISO2 country code from country name

查看:628
本文介绍了国家/地区的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"));
}

这篇关于国家/地区的ISO2国家/地区代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆