Search code examples
javalocalizationlocale

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 :)


Solution

  • 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.