Search code examples
javainternationalizationlocale

In Java, is there any way to get a Locale given its display name?


That is, if I have "English (United States)" I'd like to get "en-US", or an appropriate java.util.Locale. It looks like the API is a one-way street, but perhaps I'm not looking in the right place. Thanks in advance.


Solution

  • No, it does not appear that there is such a method in the API. However, you could create a cache using the Locales returned by Locale.getAvailableLocales(); then you can simply look up the display name in this cache.

    private static Map<String, Locale> displayNames = new HashMap<String, Locale>();
    static {
        for (Locale l : Locale.getAvailableLocales()) {
            displayNames.put(l.getDisplayName(), l);
        }
    }
    
    public static Locale getLocale(String displayName) {
        return displayNames.get(displayName);
    }