0

I am getting ISO alpha-2 country code from the server in the response of an API but I need to convert that ISO alpha-2 country code to the country name. I am using Java 8.

  • Does this answer your question? [Is there an open source java enum of ISO 3166-1 country codes](https://stackoverflow.com/questions/139867/is-there-an-open-source-java-enum-of-iso-3166-1-country-codes) – Jonn Sep 28 '21 at 15:04

2 Answers2

1

Using the below code, we can get all the countries ISO3 code and ISO2 code, and country names from Java 8 locale.

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);
    }
}

You can also create a lookup table map to convert in between ISO codes. As I need to convert between iso3 to iso2 so create the map according.

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);
    }
0

Try taking a look at the answers for this question: Is there an open source java enum of ISO 3166-1 country codes

You should be able to add a library to your application to let you get the name of a country via the code.

Jonn
  • 1,594
  • 1
  • 14
  • 25
  • I was trying to avoid open-source or 3rd party library and I found a way to convert ISO alpha-2 country code to the country name using java 8 build-in locale. – Hamza Farooq Oct 11 '21 at 16:08