Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 917
Cheezmeister Avatar asked Jun 05 '09 21:06

Cheezmeister


People also ask

How do I get the locale in Java?

To get equivalent information in Java, use Locale. getDefault() to get the Locale that Java is using, and use methods on the Locale object such as getCountry() , getLanguage() to get details. The information is available using ISO codes and as human readable/displayable names.

What is Java locale string?

A map from single character keys to string values, indicating extensions apart from language identification. The extensions in Locale implement the semantics and syntax of BCP 47 extension subtags and private use subtags.


1 Answers

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);
}
like image 81
Michael Myers Avatar answered Sep 24 '22 16:09

Michael Myers