get country code from country name in android

前端 未结 5 1240
旧时难觅i
旧时难觅i 2021-01-05 09:52

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 l

5条回答
  •  臣服心动
    2021-01-05 10:33

    public String getCountryCode(String countryName) {
    
        // Get all country codes in a string array.
        String[] isoCountryCodes = Locale.getISOCountries();
        Map 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.
    }
    

    Or a Kotlin one liner:

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

    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.

提交回复
热议问题