从Android中的国家/地区名称获取国家/地区代码 [英] get country code from country name in android

查看:445
本文介绍了从Android中的国家/地区名称获取国家/地区代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有一种方法可以从国家/地区代码中获取国家/地区名称,但是也有可能采用其他方法吗?到目前为止,我还没有找到将"Netherlands"之类的字符串转换为"NL"的函数.如果可能的话,如何获取国家代码?

I know there is a way to obtain the country name from a country code, but is it also possible the other way arround? I have found so far no function that converts a String like "Netherlands" into "NL". If possible, how can I obtain the country codes?

推荐答案

public String getCountryCode(String countryName) {

    // Get all country codes in a string array.
    String[] isoCountryCodes = Locale.getISOCountries();
    Map<String, String> countryMap = new HashMap<>();
    Locale locale; 
    String name;

    // Iterate through all country codes:
    for (String code : isoCountryCodes) {
        // Create a locale using each country code
        locale = new Locale("", code);
        // Get country name for each code.
        name = locale.getDisplayCountry();
        // Map all country names and codes in key - value pairs.
        countryMap.put(name, code);
    }

    // Return the country code for the given country name using the map.
    // Here you will need some validation or better yet 
    // a list of countries to give to user to choose from.
    return countryMap.get(countryName); // "NL" for Netherlands.
}

或者是Kotlin的一种衬垫:

Or a Kotlin one liner:

fun getCountryCode(countryName: String) = 
     Locale.getISOCountries().find { Locale("", it).displayCountry == countryName }

如注释中所述,如果您使用Java,则取决于调用此方法的频率,您可能希望从中拉出地图,但最好使用@Dambo而不使用地图来查看优化版本.

As noted in the comments, if you're using Java, depending on how often you call this method, you might want to pull the map out of it but better yet look at the optimised version by @Dambo without the map.

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

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