Using Java, is there a way to check if a given string is a valid ISO 3 letter country code? (example: check if USA is correct or not)
If possible, please provide a solution without having to make country code map.
Since Java 9 you can use Locale::getISOCountries
method, passing a flag for the 3-letter kind, Locale.IsoCountryCode.PART1_ALPHA3
.
boolean contains = Locale.getISOCountries(Locale.IsoCountryCode.PART1_ALPHA3).contains("USA");
You can use both the Local#getISOCountries() and Local#getISO3Country() methods contained within the Local class to get all the three letter country codes. Here is a method that will return a String[] Array of all the three letter country codes:
public static String[] getISO3CountryCodes() {
String[] countries = Locale.getISOCountries();
String[] iso3 = new String[countries.length];
for (int i = 0; i < countries.length; i++) {
Locale locale = new Locale("", countries[i]);
iso3[i] = locale.getISO3Country();
}
return iso3;
}
And to fire it up with a validation example:
// Get the Country Codes and place them into a Collection (List Interface)
List<String> countryCodes = java.util.Arrays.asList(getISO3CountryCodes());
System.out.println(countryCodes); //Display the collection in Console
// Get Country Code input from User and test for validity.
Scanner input = new Scanner(System.in);
String cCode = "";
while (cCode.equals("")) {
System.out.print("Enter a Country code: --> ");
cCode = input.nextLine().trim().toUpperCase();
// Is the supplied Country Code contained within the
// List. If not then it's invalid.
if (!countryCodes.contains(cCode)) {
// Nope...supplied country code is not in the List.
System.err.println("Invalid Country Code Supplied (" + cCode + ")!");
System.out.println();
cCode = ""; // Null String to ensure re-prompting
}
}
System.out.println("Valid Country Code Supplied (" + cCode + "). Thank-You");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With