views:

88

answers:

3

Using Java, Is there a quick way to convert an alpha-2 country code (IN or GB) to the alpha-3 equivalent (IND or GBR)?

I can get the alpha-2 codes with:

String[] codes = java.util.Locale.getISOLanguages();

That's not a problem, actually my application reads in the alpha-2 code, but I need to output the alpha-3 equivalent .

Is there a similar way like above to get the alpha-3 codes?

Any suggestions?

+6  A: 

Yes, simple create a Locale and get if from the locale:

String alpha3Country = new Locale("en", alpha2County).getISO3Country();

BTW: getISOLanguages() returns language codes (uppercase), getISOCountries() return country codes (lowercase)

Arne Burmeister
This is great, as I can swop in a variable containing the new country code each time, and it will give me back the corresponding 3 char code for every country. The language will all be english, but I'm not concerned about language.
Mbg
+2  A: 

This works -

    Locale locale = new Locale("en","IN");
    System.out.println("Country=" + locale.getISO3Country());

Output:

Country=IND
Gopi
This is great, as I can swop in a variable containing the new country code each time, and it will give me back the corresponding 3 char code for every country.Locale locale = new Locale("en",myCode); The language will all be english, but I'm not concerned about language.
Mbg
+3  A: 

Since you read in the codes, you can't hardcode them you rather should create a lookup table to convert into ISO codes.

public static void main(String[] args) {
        // setup
        Locale[] availableLocales = Locale.getAvailableLocales();
        HashMap<String, String> map = new HashMap<String, String>();
        for ( Locale l : availableLocales ) {
            map.put( l.getCountry(), l.getISO3Country() );
        }
        // usage
        System.out.println( map.get( "IN" ) );
        System.out.println( map.get( "GB" ) );
    }
stacker