Skip to content

Instantly share code, notes, and snippets.

@lpellegr
Created November 12, 2019 16:21
Show Gist options
  • Save lpellegr/ce8e515c0ef623dc81ce8bcf068b2b22 to your computer and use it in GitHub Desktop.
Save lpellegr/ce8e515c0ef623dc81ce8bcf068b2b22 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class LanguageTags {
public static void main(String[] args) {
Locale[] locales = Locale.getAvailableLocales();
List<LocaleEntry> entries = new ArrayList<>(locales.length);
for (Locale locale : locales) {
if ((locale.getCountry().length() == 2 || locale.getCountry().isEmpty()) && locale.getLanguage().length() == 2) {
entries.add(
new LocaleEntry(
locale.getCountry(), locale.getDisplayCountry(),
locale.getLanguage(), locale.getDisplayLanguage()));
}
}
entries.sort((a, b) -> {
int result = a.languageName.compareTo(b.languageName);
if (result == 0) {
result = a.countryName.compareTo(b.countryName);
if (result == 0) {
if (a.countryCode.isEmpty() && b.countryCode.isEmpty()) {
return 0;
}
if (a.countryCode.isEmpty()) {
return -1;
}
return 1;
}
return result;
}
return result;
});
entries.forEach(e -> System.out.println(e.toString()));
entries.forEach(e -> System.out.println(e.toJavaScript()));
}
}
class LocaleEntry {
String countryCode;
String countryName;
String languageCode;
String languageName;
LocaleEntry(String countryCode, String countryName, String languageCode, String languageName) {
this.countryCode = countryCode;
this.countryName = countryName;
this.languageCode = languageCode;
this.languageName = languageName;
}
public String toLanguageTag() {
if (countryCode.isEmpty()) {
return languageCode;
}
return languageCode + '-' + countryCode;
}
@Override
public String toString() {
if (countryCode.isEmpty()) {
return languageName + " (" + languageCode + ")";
}
return languageName + " (" + countryName + ") (" + languageCode + "-" + countryCode + ")";
}
public String toJavaScript() {
StringBuilder result = new StringBuilder();
result.append('{');
result.append("label:\"");
result.append(toString());
result.append("\",");
result.append("languageTag:\"");
result.append(toLanguageTag());
result.append("\",");
result.append("languageCode:\"");
result.append(languageCode);
result.append("\",");
result.append("languageName:\"");
result.append(languageName);
result.append("\",");
result.append("countryCode:\"");
result.append(countryCode);
result.append("\",");
result.append("countryName:\"");
result.append(countryName);
result.append("\"");
result.append("},");
return result.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment