Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an elegant way to convert ISO 639-2 (3 letter) language codes to Java Locales?

E.g. eng, spa, ita, ger

I could iterate all locales and compare the codes, but I wonder whether there is a more elegant & performant way to achieve this....

Thanks a lot for any hints :)

like image 444
PeterP Avatar asked Mar 23 '09 16:03

PeterP


2 Answers

I don't know if there's an easy way to convert the 3-letter to the 2-letter versions, but in a worse case scenario, you could create a Map of them, like so:

String[] languages = Locale.getISOLanguages();
Map<String, Locale> localeMap = new HashMap<String, Locale>(languages.length);
for (String language : languages) {
    Locale locale = new Locale(language);
    localeMap.put(locale.getISO3Language(), locale);
}

Now you can look up locales using things like localeMap.get("eng");

Edit: Modified the way the map is created. Now there should be one object per language.

Edit 2: It's been a while, but changed the code to use the actual length of the languages array when initializing the Map.

like image 107
Powerlord Avatar answered Oct 20 '22 10:10

Powerlord


You can use constructor Locale(String language), where language is the 2 letter ISO-639-1 code. I think the easiest way to convert ISO-639-2 to ISO-639-1 would be to create HashMap<String,String> constant.

like image 36
vartec Avatar answered Oct 20 '22 10:10

vartec