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

前端 未结 3 1202
轻奢々
轻奢々 2021-01-04 02:55

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

3条回答
  •  悲&欢浪女
    2021-01-04 03:32

    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 localeMap = new HashMap(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.

提交回复
热议问题