Mapping ISO2 and ISO3 Country Codes with Java

There are two commonly used code systems for countries: ISO 3166-1 alpha-2 and ISO 3166-1 alpha-3, aka ISO2 and ISO3 country codes.

In ISO 3166-1 alpha-2, each country is represented by 2 letters, and 3 letters in ISO 3166-1 alpha-3.
ISO2 and ISO3 country codes can be converted to each other, but the Java class library has no build in methods to do the conversion.

To convert ISO3 to ISO2 country codes, initialize a mapping table (call this method once):

private Map<string, Locale> localeMap;

private void initCountryCodeMapping() {
	String[] countries = Locale.getISOCountries();
	localeMap = new HashMap<string, Locale>(countries.length);
	for (String country : countries) {
		Locale locale = new Locale("", country);
		localeMap.put(locale.getISO3Country().toUpperCase(), locale);
	}
}

Now you can use the following method to do the conversion from ISO3 to ISO2:

private String iso3CountryCodeToIso2CountryCode(String iso3CountryCode) {
	return localeMap.get(iso3CountryCode).getCountry();
}

To convert ISO2 to ISO3 country codes, use the following method:

private String iso2CountryCodeToIso3CountryCode(String iso2CountryCode){
	Locale locale = new Locale("", iso2CountryCode);
	return locale.getISO3Country();
}
Short URL for this post: http://wp.me/p4nxik-lk
This entry was posted in Java and Quality and tagged , , , , , . Bookmark the permalink.

4 Responses to Mapping ISO2 and ISO3 Country Codes with Java

  1. Pingback: How to convert ISO3 Country Codes to ISO2 and vice versa with a Grails Service | Coding Snippets

  2. Ron Wheeler says:

    private Map localeMap; string->String

  3. Ivo Steinmann says:

    There is just one big problem, there are much more 3-letter language codes than 2-letter codes. Therefore using Locale.getISOCountries() to build a list of 3-letter codes results in an incomplete list. It is just a subset of the complete table. There are many 3-letter codes with no 2-letter representation.

    • tismo says:

      You’re right. Nevertheless, at least JAVA 8 uses a mappish string internally that maps from ISO2 to ISO3. So when a pure JDK/JRE solution is what you’re after, it’s actually completely sufficient.

Leave a Reply