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.
how can i get Country name from ISO3166-1 alpha-2 country code in java
3k Views Asked by Hamza Farooq At
2
There are 2 best solutions below
0
On
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);
}
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.