Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iso 3 letter country code validation in JAVA

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.

like image 310
Coder_99 Avatar asked Jan 24 '23 21:01

Coder_99


2 Answers

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");
like image 155
User9123 Avatar answered Jan 31 '23 19:01

User9123


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");
like image 28
DevilsHnd Avatar answered Jan 31 '23 18:01

DevilsHnd