Locale Available ISOCountries Listing
List the ISO country and language codes the JDK knows with getISOCountries and getISOLanguages, then validate user input against those sets.
Code
import java.util.Arrays;
import java.util.Locale;
import java.util.Set;
import java.util.TreeSet;
public class CountryGate {
public static void main(String[] args) {
// getISOCountries(ISO3166):JDK 内置的两字母国家码全集
Set<String> countries = new TreeSet<>(Arrays.asList(Locale.getISOCountries()));
Set<String> languages = new TreeSet<>(Arrays.asList(Locale.getISOLanguages()));
System.out.println("country count: " + countries.size());
System.out.println("language count: " + languages.size());
System.out.println("first countries: " + countries.stream().limit(5).toList());
// 用户提交的国家码先大写再校验,避免 'de' 被误拒
for (String submitted : new String[] {"DE", "de", "ZZ", "us"}) {
boolean valid = countries.contains(submitted.toUpperCase(Locale.ROOT));
System.out.println(submitted + " -> " + (valid ? "accepted" : "rejected"));
}
System.out.println("has language 'zh': " + languages.contains("zh"));
}
}The workings of the snippet
The snippet is organized around the class CountryGate and the function main.
The loop for (String submitted : new String[] {"DE", "de", "ZZ", "us"}) is the only repeated construct. The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.
Watch out for
- Zero packages pulled in — the runtime ships every API this code touches.
Putting it to use
Entry signature: public static void main(String[] args)
The file’s steps show up in the output as country count:, language count:, first countries:.
Core lines
Set<String> countries = new TreeSet<>(Arrays.asList(Locale.getISOCountries()));
Set<String> languages = new TreeSet<>(Arrays.asList(Locale.getISOLanguages()));
boolean valid = countries.contains(submitted.toUpperCase(Locale.ROOT));
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- What does Locale Available ISOCountries Listing print when run?
- Running the file directly is enough — expect labeled output lines such as `country count:`, `language count:`, `first countries:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.