在 Java 中从语言环境创建 Locale.LanguageRange 的标准方法

tim*_*ley 5 java localization java-8

在 Java 中有没有办法从语言环境创建 Locale.LanguageRange?

目前我这样做:

List<LanguageRange> ranges = 
        Locale.LanguageRange.parse(
                locale.toString()  // locale.toString() gives en_GB
                .replace('_', '-') // parse() needs en-GB
                + ";q=1.0");       // weight
Run Code Online (Sandbox Code Playgroud)

感觉很脏,很不雅观。

有没有更好甚至标准的方法来做到这一点?我找不到一个。

最小工作示例:

import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Locale.LanguageRange;

public class LanguageUtil {
        public static Locale getClosestMatch(Locale locale, Locale defaultLocale, Collection<Locale> allowedLanguages) {
            List<LanguageRange> ranges = Locale.LanguageRange.parse(
                    locale.toString().replace('_', '-') + ";q=1.0," +           //exact match e.g. en-GB -> en-GB
                    locale.getLanguage() + ";q=0.5," +                          //close match e.g. en-US -> en-GB
                    defaultLocale.toString().replace('_', '-') + ";q=0.0"));    //default match e.g. fr-FR -> en-GB
            return Locale.filter(ranges, allowedLanguages).get(0);
        }
    }
Run Code Online (Sandbox Code Playgroud)

Jen*_*gsa 5

我习惯从 anew LanguageRange(locale.toLanguageTag())派生 a来处理语法。LanguageRangeLocale

然而,将其提供给Locale.lookup()匹配是有限制的(它不会返回en_GBen

因此,我最终采用了一个两步机制:

  1. filter所有系统区域设置(按请求的区域设置)
  2. lookup第 1 步的结果列表中与支持的区域设置的最佳匹配

源代码:

List<Locale> allAvailableLocales = Arrays.asList(Locale.getAvailableLocales());

private Locale findBestMatch(final List<Locale> requested, final List<Locale> supported) {
    final List<LanguageRange> languageRanges = toLanguageRanges(requested);

    final List<Locale> allMatches = Locale.filter(languageRanges, allAvailableLocales);
    final Locale bestMatch = Locale.lookup(toLanguageRanges(allMatches), supported);

    return bestMatch;
}

private static List<LanguageRange> toLanguageRanges(final List<Locale> locales) {
    final ArrayList<LanguageRange> languageRanges = new ArrayList<>();
    for (final Locale locale : locales) {
        languageRanges.add(toLanguageRange(locale));
    }
    return languageRanges;
}

private static LanguageRange toLanguageRange(final Locale locale) {
    return new LanguageRange(locale.toLanguageTag());
}
Run Code Online (Sandbox Code Playgroud)

findBestMatch注意:如果返回,请考虑默认值null