Locale Filter Negotiates Language List

Match an Accept-Language header against supported locales: Locale.filter returns all matches, Locale.lookup picks the single best one by weight.

JavaData Integrity

Code

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

public class LanguageNegotiator {

    public static void main(String[] args) {
        List<Locale> supported = List.of(
                Locale.forLanguageTag("zh-CN"),
                Locale.forLanguageTag("zh-Hant-TW"),
                Locale.US,
                Locale.forLanguageTag("ko-KR"));

        // an Accept-Language style preference list: q values carry the weights
        String accept = "zh-TW;q=0.9, zh;q=0.8, en;q=0.5";

        // filter returns every matching candidate; lookup picks the single best by weight
        List<Locale> matches = Locale.filter(
                LanguageRange.parse(accept), supported);
        Locale best = Locale.lookup(
                LanguageRange.parse(accept), supported);

        System.out.println("matches: " + matches);
        System.out.println("picked : " + best);
    }
}

How it works

Locale Filter Negotiates Language List comes down to the class LanguageNegotiator and the function main.

Putting it to use

The demo output is labeled (matches:, picked :), so every printed line maps back to its originating operation.

Core lines

List<Locale> matches = Locale.filter(
LanguageRange.parse(accept), supported);

Interactive Tools for This Topic

FAQ

What does Locale Filter Negotiates Language List print when run?
Run it as a complete program — the output lines carry labels such as `matches:`, `picked :`.