Wednesday, December 31, 2008

Locale.getDefault() to get default locale

To get the default Locale of the host JVM invoke Locale.getDefault()

Creating a unique, sorted list of countries in Java

Following code snippets creates a hash of unique, sorted country names with the country name as the key and ISO 639 country code as the value


Locale[] allCountries = Locale.getAvailableLocales();
Map uniqueCountries = new TreeMap();
for (Locale currentCountry : allCountries)
{
if (! "".equals(currentCountry.getISO3Country()))
{
String countryName =
currentCountry.getDisplayCountry(
FacesContext.getCurrentInstance().getViewRoot(
).getLocale());
uniqueCountries.put(
countryName, currentCountry.getISO3Country());
}
}


Then you can use the map to do whatever. Here is an example to generate a list of JSF SelectItems

List countrySelectItems = new LinkedList();

for (String currentCountryCode : uniqueCountries.keySet())
{
countrySelectItems.add(
new SelectItem(
uniqueCountries.get(currentCountryCode),
currentCountryCode
)
);
}