Is there an easy way in Java to get the ISO2 code from a given country name, for example "CH" when given "Switzerland"?
The only solution I can think of at the moment is to save all the country codes and names in an array and iterate over it. Any other (easier) solutions?
You could use the built-in Locale
class:
Locale l = new Locale("", "CH");
System.out.println(l.getDisplayCountry());
prints "Switzerland" for example. Note that I have not provided a language.
So what you can do for the reverse lookup is build a map from the available countries:
public static void main(String[] args) throws InterruptedException {
Map<String, String> countries = new HashMap<>();
for (String iso : Locale.getISOCountries()) {
Locale l = new Locale("", iso);
countries.put(l.getDisplayCountry(), iso);
}
System.out.println(countries.get("Switzerland"));
System.out.println(countries.get("Andorra"));
System.out.println(countries.get("Japan"));
}