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:

package grimey.com;

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

final class CountryService {
private final Map countryToISOMap;

public CountryService() {
countryToISOMap = Arrays
.stream(Locale.getISOCountries())
.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, "");
}
}

Advertisements