get country code from country name in android

Tristus picture Tristus · Feb 13, 2015 · Viewed 15k times · Source

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?

Answer

Vlad picture Vlad · Jul 26, 2016
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.
}

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.