2

I have some country variable, "France" for example. I want to get the country code, in this example, I want to get "FR" or "fr".

I tried :

 Locale locale = new Locale("", "FRANCE");
 Log.e("test", locale.getCountry());

But it returns :

 FRANCE

What I'm missing ?

Thank you !

Xero
  • 3,951
  • 4
  • 41
  • 73

1 Answers1

3

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"));
}

Answer found on this post. Hope it helps.

palsch
  • 5,528
  • 4
  • 21
  • 32
Kristo
  • 1,339
  • 12
  • 22