java-8 - 我如何从 java 中的 ISO3166-1 alpha-2 国家代码中获取国家名称
问题描述
我在 API 的响应中从服务器获取ISO alpha-2 国家代码,但我需要将该ISO alpha-2 国家代码转换为国家名称。我正在使用 Java 8。
解决方案
使用下面的代码,我们可以从 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);
}
推荐阅读
- java - 如何注入在 Guice 中使用辅助注入创建的对象?
- r - 使用二进制变量创建计数器
- solr - 如何为布尔值添加 Hybris Solr By
- ansible - 使用 Ansible 循环访问已注册的文件模块数据
- api - 反向地理编码 - minresults 不适用于模式类型 retrieveAreas
- swagger - 没有为从基类继承的控制器生成 swagger.json
- android - 从片段返回活动的正确方法是什么
- javascript - 如何使 div 具有溢出 y 滚动响应(高度方面)?
- mysql - JOIN 顺序影响 3 表内连接选择查询中的性能
- symfony4 - FormType 中的实体属性定义