views:

1967

answers:

4

Does anyone know of a freely available java 1.5 package that provides a list of ISO 3166-1 country codes as a enum or EnumMap? Specifically I need the "ISO 3166-1-alpha-2 code elements", i.e. the 2 character country code like "us", "uk", "de", etc. Creating one is simple enough (although tedious), but if there's a standard one already out there in apache land or the like it would save a little time.

A: 

The best I can see is:

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

Which returns a list of all 2-letter language codes defined in ISO 639.

tim_yates
I think you mean Locale.getISOCountries()
McDowell
+6  A: 

This code gets 242 countries in Sun Java 6:

String[] countryCodes = Locale.getISOCountries();

Though the ISO website claims there are 246 ISO 3166-1-alpha-2 code elements, though the javadoc links to the same information.

McDowell
This information is hardcoded. You would need to update JRE regulary to keep updated :)
BalusC
+1  A: 

There is an easy way to generate this enum with the language name. Execute this code to generate the list of enum fields to paste :

 /**
  * This is the code used to generate the enum content
  */
 public static void main(String[] args) {
  String[] codes = java.util.Locale.getISOLanguages();
  for (String isoCode: codes) {
   Locale locale = new Locale(isoCode);
   System.out.println(isoCode.toUpperCase() + "(\"" + locale.getDisplayLanguage(locale) + "\"),");
  }
 }
Christophe Desguez
This gives you a list of languages, not countries.
A: 

Here's how I generated an enum with country code + country name:

package countryenum;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

public class CountryEnumGenerator {
    public static void main(String[] args) {
        String[] countryCodes = Locale.getISOCountries();
        List<Country> list = new ArrayList<Country>(countryCodes.length);

        for (String cc : countryCodes) {
            list.add(new Country(cc.toUpperCase(), new Locale("", cc).getDisplayCountry()));
        }

        Collections.sort(list);

        for (Country c : list) {
            System.out.println(c.getCode() + "(\"" + c.getName() + "\"),");
        }

    }
}

class Country implements Comparable<Country> {
    private String code;
    private String name;

    public Country(String code, String name) {
        super();
        this.code = code;
        this.name = name;
    }

    public String getCode() {
        return code;
    }


    public void setCode(String code) {
        this.code = code;
    }


    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }


    @Override
    public int compareTo(Country o) {
        return this.name.compareTo(o.name);
    }
}
Bozho