Country name to ISO code mapper

I was looking for a library that allowed me to pass in a country name and get the ISO code for it.
Unfortunately I couldn’t find one, so I wrote a tiny bit of code to achieve this without having to create a huge hard coded map like most of the threads on Stack Overflow suggest.

Here’s the code:


import java.util.Arrays;
import java.util.Locale;
import java.util.Map;

final class CountryService {
private final Map countryToISOMap;

public CountryService() {
countryToISOMap = Arrays
.collect(Collectors.toMap(isoCode -> {
final Locale locale = new Locale("", isoCode);

return locale.getDisplayCountry();
}, isoCode -> isoCode));

public String countryToISO(final String country) {
return countryToISOMap.getOrDefault(country, "");


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s