52

Is there an easy way in Java to get the ISO2 code from a given country name, for example "CH" when given "Switzerland"?

The only solution I can think of at the moment is to save all the country codes and names in an array and iterate over it. Any other (easier) solutions?

Chris
  • 1,316
  • 2
  • 13
  • 20
  • 1
    Sorry, both don't answer my question. I was looking for an EASY way (maybe without saving all the names+codes in an array/Map) to get the code from the country name, so the other way round. – Chris Jan 04 '13 at 10:21

12 Answers12

77

You could use the built-in Locale class:

Locale l = new Locale("", "CH");
System.out.println(l.getDisplayCountry());

prints "Switzerland" for example. Note that I have not provided a language.

So what you can do for the reverse lookup is build a map from the available countries:

public static void main(String[] args) throws InterruptedException {
    Map<String, String> countries = new HashMap<>();
    for (String iso : Locale.getISOCountries()) {
        Locale l = new Locale("", iso);
        countries.put(l.getDisplayCountry(), iso);
    }

    System.out.println(countries.get("Switzerland"));
    System.out.println(countries.get("Andorra"));
    System.out.println(countries.get("Japan"));
}
assylias
  • 321,522
  • 82
  • 660
  • 783
  • 5
    Note that this **WILL** break if your phone is set to a language other than English. `Locale.getDisplayLocale()` is equivalent to `Locale.getDisplayLocale(Locale.getDefaultLocale());` If you want a map from country names in a specific language to ISO (or the other way around) you need to do something like `localizedCountries.put(new Locale("en", iso).getDisplayCountry(new Locale("en", iso)), new Locale(Locale.getDefault().getLanguage(), iso).getDisplayCountry());` where you replace "en" with whatever language's two-letter code.. – Fab Castel Jul 22 '15 at 17:44
  • 2
    Note that the code I posted above creates a map from country names in English to country names in whatever language the phone is set to. That's what I'd set out to do originally and what landed me here, but you can easily adapt my solution to answer the original problem. – Fab Castel Jul 22 '15 at 17:45
21

As others have mentioned Map is the easiest way, here's what I wrote/used where I had the same problem.

 import java.util.Map;
 import java.util.TreeMap;


 public class CountryCodes {
     final Map<String, String> map = new TreeMap<String, String>   (String.CASE_INSENSITIVE_ORDER);
    public CountryCodes() {

     map.put("Andorra, Principality Of", "AD");
     map.put("United Arab Emirates", "AE");
     map.put("Afghanistan, Islamic State Of", "AF");
     map.put("Antigua And Barbuda", "AG");
     map.put("Anguilla", "AI");
     map.put("Albania", "AL");
     map.put("Armenia", "AM");
     map.put("Netherlands Antilles", "AN");
     map.put("Angola", "AO");
     map.put("Antarctica", "AQ");
     map.put("Argentina", "AR");
     map.put("American Samoa", "AS");
     map.put("Austria", "AT");
     map.put("Australia", "AU");
     map.put("Aruba", "AW");
     map.put("Azerbaidjan", "AZ");
     map.put("Bosnia-Herzegovina", "BA");
     map.put("Barbados", "BB");
     map.put("Bangladesh", "BD");
     map.put("Belgium", "BE");
     map.put("Burkina Faso", "BF");
     map.put("Bulgaria", "BG");
     map.put("Bahrain", "BH");
     map.put("Burundi", "BI");
     map.put("Benin", "BJ");
     map.put("Bermuda", "BM");
     map.put("Brunei Darussalam", "BN");
     map.put("Bolivia", "BO");
     map.put("Brazil", "BR");
     map.put("Bahamas", "BS");
     map.put("Bhutan", "BT");
     map.put("Bouvet Island", "BV");
     map.put("Botswana", "BW");
     map.put("Belarus", "BY");
     map.put("Belize", "BZ");
     map.put("Canada", "CA");
     map.put("Cocos (Keeling) Islands", "CC");
     map.put("Central African Republic", "CF");
     map.put("Congo, The Democratic Republic Of The", "CD");
     map.put("Congo", "CG");
     map.put("Switzerland", "CH");
     map.put("Ivory Coast (Cote D'Ivoire)", "CI");
     map.put("Cook Islands", "CK");
     map.put("Chile", "CL");
     map.put("Cameroon", "CM");
     map.put("China", "CN");
     map.put("Colombia", "CO");
     map.put("Costa Rica", "CR");
     map.put("Former Czechoslovakia", "CS");
     map.put("Cuba", "CU");
     map.put("Cape Verde", "CV");
     map.put("Christmas Island", "CX");
     map.put("Cyprus", "CY");
     map.put("Czech Republic", "CZ");
     map.put("Germany", "DE");
     map.put("Djibouti", "DJ");
     map.put("Denmark", "DK");
     map.put("Dominica", "DM");
     map.put("Dominican Republic", "DO");
     map.put("Algeria", "DZ");
     map.put("Ecuador", "EC");
     map.put("Estonia", "EE");
     map.put("Egypt", "EG");
     map.put("Western Sahara", "EH");
     map.put("Eritrea", "ER");
     map.put("Spain", "ES");
     map.put("Ethiopia", "ET");
     map.put("Finland", "FI");
     map.put("Fiji", "FJ");
     map.put("Falkland Islands", "FK");
     map.put("Micronesia", "FM");
     map.put("Faroe Islands", "FO");
     map.put("France", "FR");
     map.put("France (European Territory)", "FX");
     map.put("Gabon", "GA");
     map.put("Great Britain", "UK");
     map.put("Grenada", "GD");
     map.put("Georgia", "GE");
     map.put("French Guyana", "GF");
     map.put("Ghana", "GH");
     map.put("Gibraltar", "GI");
     map.put("Greenland", "GL");
     map.put("Gambia", "GM");
     map.put("Guinea", "GN");
     map.put("Guadeloupe (French)", "GP");
     map.put("Equatorial Guinea", "GQ");
     map.put("Greece", "GR");
     map.put("S. Georgia & S. Sandwich Isls.", "GS");
     map.put("Guatemala", "GT");
     map.put("Guam (USA)", "GU");
     map.put("Guinea Bissau", "GW");
     map.put("Guyana", "GY");
     map.put("Hong Kong", "HK");
     map.put("Heard And McDonald Islands", "HM");
     map.put("Honduras", "HN");
     map.put("Croatia", "HR");
     map.put("Haiti", "HT");
     map.put("Hungary", "HU");
     map.put("Indonesia", "ID");
     map.put("Ireland", "IE");
     map.put("Israel", "IL");
     map.put("India", "IN");
     map.put("British Indian Ocean Territory", "IO");
     map.put("Iraq", "IQ");
     map.put("Iran", "IR");
     map.put("Iceland", "IS");
     map.put("Italy", "IT");
     map.put("Jamaica", "JM");
     map.put("Jordan", "JO");
     map.put("Japan", "JP");
     map.put("Kenya", "KE");
     map.put("Kyrgyz Republic (Kyrgyzstan)", "KG");
     map.put("Cambodia, Kingdom Of", "KH");
     map.put("Kiribati", "KI");
     map.put("Comoros", "KM");
     map.put("Saint Kitts & Nevis Anguilla", "KN");
     map.put("North Korea", "KP");
     map.put("South Korea", "KR");
     map.put("Kuwait", "KW");
     map.put("Cayman Islands", "KY");
     map.put("Kazakhstan", "KZ");
     map.put("Laos", "LA");
     map.put("Lebanon", "LB");
     map.put("Saint Lucia", "LC");
     map.put("Liechtenstein", "LI");
     map.put("Sri Lanka", "LK");
     map.put("Liberia", "LR");
     map.put("Lesotho", "LS");
     map.put("Lithuania", "LT");
     map.put("Luxembourg", "LU");
     map.put("Latvia", "LV");
     map.put("Libya", "LY");
     map.put("Morocco", "MA");
     map.put("Monaco", "MC");
     map.put("Moldavia", "MD");
     map.put("Madagascar", "MG");
     map.put("Marshall Islands", "MH");
     map.put("Macedonia", "MK");
     map.put("Mali", "ML");
     map.put("Myanmar", "MM");
     map.put("Mongolia", "MN");
     map.put("Macau", "MO");
     map.put("Northern Mariana Islands", "MP");
     map.put("Martinique (French)", "MQ");
     map.put("Mauritania", "MR");
     map.put("Montserrat", "MS");
     map.put("Malta", "MT");
     map.put("Mauritius", "MU");
     map.put("Maldives", "MV");
     map.put("Malawi", "MW");
     map.put("Mexico", "MX");
     map.put("Malaysia", "MY");
     map.put("Mozambique", "MZ");
     map.put("Namibia", "NA");
     map.put("New Caledonia (French)", "NC");
     map.put("Niger", "NE");
     map.put("Norfolk Island", "NF");
     map.put("Nigeria", "NG");
     map.put("Nicaragua", "NI");
     map.put("Netherlands", "NL");
     map.put("Norway", "NO");
     map.put("Nepal", "NP");
     map.put("Nauru", "NR");
     map.put("Neutral Zone", "NT");
     map.put("Niue", "NU");
     map.put("New Zealand", "NZ");
     map.put("Oman", "OM");
     map.put("Panama", "PA");
     map.put("Peru", "PE");
     map.put("Polynesia (French)", "PF");
     map.put("Papua New Guinea", "PG");
     map.put("Philippines", "PH");
     map.put("Pakistan", "PK");
     map.put("Poland", "PL");
     map.put("Saint Pierre And Miquelon", "PM");
     map.put("Pitcairn Island", "PN");
     map.put("Puerto Rico", "PR");
     map.put("Portugal", "PT");
     map.put("Palau", "PW");
     map.put("Paraguay", "PY");
     map.put("Qatar", "QA");
     map.put("Reunion (French)", "RE");
     map.put("Romania", "RO");
     map.put("Russian Federation", "RU");
     map.put("Rwanda", "RW");
     map.put("Saudi Arabia", "SA");
     map.put("Solomon Islands", "SB");
     map.put("Seychelles", "SC");
     map.put("Sudan", "SD");
     map.put("Sweden", "SE");
     map.put("Singapore", "SG");
     map.put("Saint Helena", "SH");
     map.put("Slovenia", "SI");
     map.put("Svalbard And Jan Mayen Islands", "SJ");
     map.put("Slovak Republic", "SK");
     map.put("Sierra Leone", "SL");
     map.put("San Marino", "SM");
     map.put("Senegal", "SN");
     map.put("Somalia", "SO");
     map.put("Suriname", "SR");
     map.put("Saint Tome (Sao Tome) And Principe", "ST");
     map.put("Former USSR", "SU");
     map.put("El Salvador", "SV");
     map.put("Syria", "SY");
     map.put("Swaziland", "SZ");
     map.put("Turks And Caicos Islands", "TC");
     map.put("Chad", "TD");
     map.put("French Southern Territories", "TF");
     map.put("Togo", "TG");
     map.put("Thailand", "TH");
     map.put("Tadjikistan", "TJ");
     map.put("Tokelau", "TK");
     map.put("Turkmenistan", "TM");
     map.put("Tunisia", "TN");
     map.put("Tonga", "TO");
     map.put("East Timor", "TP");
     map.put("Turkey", "TR");
     map.put("Trinidad And Tobago", "TT");
     map.put("Tuvalu", "TV");
     map.put("Taiwan", "TW");
     map.put("Tanzania", "TZ");
     map.put("Ukraine", "UA");
     map.put("Uganda", "UG");
     map.put("United Kingdom", "UK");
     map.put("USA Minor Outlying Islands", "UM");
     map.put("United States", "US");
     map.put("Uruguay", "UY");
     map.put("Uzbekistan", "UZ");
     map.put("Holy See (Vatican City State)", "VA");
     map.put("Saint Vincent & Grenadines", "VC");
     map.put("Venezuela", "VE");
     map.put("Virgin Islands (British)", "VG");
     map.put("Virgin Islands (USA)", "VI");
     map.put("Vietnam", "VN");
     map.put("Vanuatu", "VU");
     map.put("Wallis And Futuna Islands", "WF");
     map.put("Samoa", "WS");
     map.put("Yemen", "YE");
     map.put("Mayotte", "YT");
     map.put("Yugoslavia", "YU");
     map.put("South Africa", "ZA");
     map.put("Zambia", "ZM");
     map.put("Zaire", "ZR");
     map.put("Zimbabwe", "ZW");

    }

     public String getCode(String country){
     String countryFound = map.get(country);
     if(countryFound==null){
             countryFound="UK";
     }
     return countryFound;
     }
}
Mark
  • 2,423
  • 4
  • 24
  • 40
  • 1
    is this intended? map.put("", "EDU EDUCATIONAL "); – Buffalo May 13 '13 at 12:05
  • 2
    I'm sceptical that this will work - if the user puts in Afghanistan instead of "Afghanistan, Islamic State Of", the map will pick up nothing? – Simon Oct 13 '15 at 18:24
  • 2
    Please keep in mind that countries can change over time (add/remove, they change their name, etc.); so from my point of view it is not a good idea to hard code a country list... – Ben Nov 30 '15 at 12:22
15

CountryCode enum contained in com.neovisionaries:nv-i18n:1.11 (or later) has findByName methods to list up country codes whose names match a given pattern.

List<CountryCode> findByName(String regex);
List<CountryCode> findByName(Pattern pattern);

To get "CH" from "Switzerland":

String code =  CountryCode.findByName("Switzerland").get(0).name();


GitHub

https://github.com/TakahikoKawasaki/nv-i18n

JavaDoc

http://takahikokawasaki.github.io/nv-i18n/

Maven

<dependency>
    <groupId>com.neovisionaries</groupId>
    <artifactId>nv-i18n</artifactId>
    <version>1.11</version>
</dependency>
Takahiko Kawasaki
  • 18,118
  • 9
  • 62
  • 105
11

Use a Map, not an array, then you don't have to iterate over it, you just look it up.

O(1) vs O(n)

//Do this once
Map<String,Locale> map = new HashMap<String,Locale>();
for (Locale locale : Locale.getAvailableLocales()) {
  map.put(locale.getDisplayCountry(), locale);
}
Qwerky
  • 18,217
  • 6
  • 44
  • 80
  • Dang, you beat me to it. Of course, this assumes that you standardize the country names - `USA`, `U.S.A.`, `US of A` and `United States of America` won't go well together. – user Jan 04 '13 at 10:15
  • I assume that there's a standardization. – Chris Jan 04 '13 at 10:22
  • 1
    That only partially answers the question - using a map as a data structure is a good idea, but that does not explain how to populate the map (where to get the data). – assylias Jan 04 '13 at 10:23
  • 1
    I think getting the data is no problem: http://www.java2s.com/Code/Java/I18N/Getalistofcountrynames.htm – Chris Jan 04 '13 at 10:25
  • 1
    @Chris - when it comes to user-input, it's never good to assume they'll conform to a standard. – SDC Jan 04 '13 at 10:25
  • You're right. I'm using a drop down list with standardized values so user input is no problem. Just as you said ;) – Chris Jan 04 '13 at 10:28
7

This is definitely the answer you are looking for, it is late but hopefully it will hepl someone

String[] isoCountries = Locale.getISOCountries();
    for (String country : isoCountries) {
        Locale locale = new Locale("en", country);
        String iso = locale.getISO3Country();
        String code = locale.getCountry();
        String name = locale.getDisplayCountry();
        System.out.println(iso + " " + code + " " + name);

    }

I have added the print statement so that you can get a good look at the result. You can substitute "CH" for that country variable in the third line and it will give you "Afghanistan".

Adindu Stevens
  • 2,947
  • 3
  • 14
  • 20
4

Nope, you've got the easy solution already: The array (or DB table, or a keyed structure like a hash map) solution is pretty much the standard way of doing this. I guess there may also be some web services available that can provide the list, but I think that would be overkill (its not worth relying on a third party system to be working for something this simple). Similar arrays would be used for lists of counties/provinces/states within a country if you needed that level of detail.

The only thing to beware of with that is if you're accepting the country name as user input, you'll need to watch for spelling errors, incorrect capitalisation, and using alternative names for countries (eg "Switzerland" could legitimately be referred to as "Schweiz" or "Suisse" or "The Swiss Confederation", or a number of other variants.

More commonly, user input is restricted to known country codes by providing a drop-list so that the user picks the country he wants and the program knows immediately that it is "CH". This also requires the same array to be in place, but is referenced in the other direction, and is more reliable (since there is only one possible code for each country).

Also note that although the list of countries in the world doesn't change much, it does change. You should make sure you keep it up-to-date.

SDC
  • 14,192
  • 2
  • 35
  • 48
3
public static void main(String[] args) throws Exception {
    System.out.println(getCountryCodeFromName("Switzerland"));
}

public static String getCountryCodeFromName(String country) {
    return Arrays.asList(Locale.getISOCountries())
            .stream()
            .map((s) -> new Locale("", s))
            .filter((l) -> l.getDisplayCountry().toLowerCase().equals(country.toLowerCase()))
            .findFirst()
            .map((l) -> l.getCountry().toLowerCase())
            .orElse("UNKNOWN");
}

note that you will walk the stream every time you call the method, it is more efficient to use a map or save the result in a lookup table

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
DrAhmedJava
  • 731
  • 8
  • 16
1

I guess the easiest Java 8+ way is to use Java's Locale class.

Two simple methods to match every country in every language.

public static Optional<String> getCountryCodeByName(String name, String lang){
    Optional<Locale> locale = getLocaleByName(name,lang);
    return locale.map(Locale::getCountry);
}

public static Optional<Locale> getLocaleByName(String name, String lang){
    return Arrays.stream(Locale.getAvailableLocales())
            .filter(l -> l.getDisplayCountry(Locale.forLanguageTag(lang)).equalsIgnoreCase(name))
            .findFirst();
}
Markus G.
  • 1,620
  • 2
  • 25
  • 49
0

concat flag to url(https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/0.8.2/flags/1x1/)

INSERT INTO `countries` (`name`, `code`, `c_code`, `flag`) VALUES

('Afghanistan', '+93', 'AF', 'af.svg'),
('Albania', '+355', 'AL', 'al.svg'),
('Algeria', '+213', 'DZ', 'dz.svg'),
('American Samoa', '+1 684', 'AS', 'as.svg'),
('Andorra', '+376', 'AD', 'ad.svg'),
('Angola', '+244', 'AO', 'ao.svg'),
('Anguilla', '+1 264', 'AI', 'ai.svg'),
('Antigua and Barbuda', '+1 268', 'AG', 'ag.svg'),
('Argentina', '+54', 'AR', 'ar.svg'),
('Armenia', '+374', 'AM', 'am.svg'),
('Aruba', '+297', 'AW', 'aw.svg'),
('Australia', '+61', 'AU', 'au.svg'),
('Austria', '+43', 'AT', 'at.svg'),
('Azerbaijan', '+994', 'AZ', 'az.svg'),
('Bahamas', '+1 242', 'BS', 'bs.svg'),
('Bahrain', '+973', 'BH', 'bh.svg'),
('Bangladesh', '+880', 'BD', 'bd.svg'),
('Barbados', '+1 246', 'BB', 'bb.svg'),
('Belarus', '+375', 'BY', 'by.svg'),
('Belgium', '+32', 'BE', 'be.svg'),
('Belize', '+501', 'BZ', 'bz.svg'),
('Benin', '+229', 'BJ', 'bj.svg'),
('Bermuda', '+1 441', 'BM', 'bm.svg'),
('Bhutan', '+975', 'BT', 'bt.svg'),
('Bolivia', '+591', 'BO', 'bo.svg'),
('Bosnia and Herzegovina', '+387', 'BA', 'ba.svg'),
('Botswana', '+267', 'BW', 'bw.svg'),
('Brazil', '+55', 'BR', 'br.svg'),
('British Indian Ocean Territory', '+246', 'IO', 'io.svg'),
('British Virgin Islands', '+1 284', 'VG', 'vg.svg'),
('Brunei', '+673', 'BN', 'bn.svg'),
('Bulgaria', '+359', 'BG', 'bg.svg'),
('Burkina Faso', '+226', 'BF', 'bf.svg'),
('Burundi', '+257', 'BI', 'bi.svg'),
('Cambodia', '+855', 'KH', 'kh.svg'),
('Cameroon', '+237', 'CM', 'cm.svg'),
('Canada', '+1', 'CA', 'ca.svg'),
('Cape Verde', '+238', 'CV', 'cv.svg'),
('Cayman Islands', '+ 345', 'KY', 'ky.svg'),
('Central African Republic', '+236', 'CF', 'cf.svg'),
('Chad', '+235', 'TD', 'td.svg'),
('Chile', '+56', 'CL', 'cl.svg'),
('China', '+86', 'CN', 'cn.svg'),
('Christmas Island', '+61', 'CX', 'cx.svg'),
('Colombia', '+57', 'CO', 'co.svg'),
('Comoros', '+269', 'KM', 'km.svg'),
('Congo', '+242', 'CG', 'cg.svg'),
('Congo, Dem. Rep. of (Zaire)', '+243', 'CD', 'cd.svg'),
('Cook Islands', '+682', 'CK', 'ck.svg'),
('Costa Rica', '+506', 'CR', 'cr.svg'),
('Croatia', '+385', 'HR', 'hr.svg'),
('Cuba', '+53', 'CU', 'cu.svg'),
('Curacao', '+599', 'CW', 'cw.svg'),
('Cyprus', '+537', 'CY', 'cy.svg'),
('Czech Republic', '+420', 'CZ', 'cz.svg'),
('Denmark', '+45', 'DK', 'dk.svg'),
('Djibouti', '+253', 'DJ', 'dj.svg'),
('Dominica', '+1 767', 'DM', 'dm.svg'),
('Dominican Republic', '+1 809', 'DO', 'do.svg'),
('East Timor', '+670', 'TR', 'tr.svg'),
('Ecuador', '+593', 'EC', 'ec.svg'),
('Egypt', '+20', 'EG', 'eg.svg'),
('El Salvador', '+503', 'SV', 'sv.svg'),
('Equatorial Guinea', '+240', 'GQ', 'gq.svg'),
('Eritrea', '+291', 'ER', 'er.svg'),
('Estonia', '+372', 'EE', 'ee.svg'),
('Ethiopia', '+251', 'ET', 'et.svg'),
('Falkland Islands', '+500', 'FK', 'fk.svg'),
('Faroe Islands', '+298', 'FO', 'fo.svg'),
('Fiji', '+679', 'FJ', 'fj.svg'),
('Finland', '+358', 'FI', 'fi.svg'),
('France', '+33', 'FR', 'fr.svg'),
('French Guiana', '+594', 'GF', 'gf.svg'),
('French Polynesia', '+689', 'PF', 'pf.svg'),
('Gabon', '+241', 'GA', 'ga.svg'),
('Gambia', '+220', 'GM', 'gm.svg'),
('Georgia', '+995', 'GE', 'ge.svg'),
('Germany', '+49', 'DE', 'de.svg'),
('Ghana', '+233', 'GH', 'gh.svg'),
('Gibraltar', '+350', 'GI', 'gi.svg'),
('Greece', '+30', 'GR', 'gr.svg'),
('Greenland', '+299', 'GL', 'gl.svg'),
('Grenada', '+1 473', 'GD', 'gd.svg'),
('Guadeloupe', '+590', 'GP', 'gp.svg'),
('Guam', '+1 671', 'GU', 'gu.svg'),
('Guatemala', '+502', 'GT', 'gt.svg'),
('Guinea', '+224', 'GN', 'gn.svg'),
('Guinea-Bissau', '+245', 'GW', 'gw.svg'),
('Guyana', '+595', 'GY', 'gy.svg'),
('Haiti', '+509', 'HT', 'ht.svg'),
('Honduras', '+504', 'HN', 'hn.svg'),
('Hong Kong', '+852', 'HK', 'hk.svg'),
('Hungary', '+36', 'HU', 'hu.svg'),
('Iceland', '+354', 'IS', 'is.svg'),
('India', '+91', 'IN', 'in.svg'),
('Indonesia', '+62', 'ID', 'id.svg'),
('Iran', '+98', 'IR', 'ir.svg'),
('Iraq', '+964', 'IQ', 'iq.svg'),
('Ireland', '+353', 'IE', 'ie.svg'),
('Israel', '+972', 'IL', 'il.svg'),
('Italy', '+39', 'IT', 'it.svg'),
('Ivory Coast', '+225', 'CI', 'ci.svg'),
('Jamaica', '+1 876', 'JM', 'jm.svg'),
('Japan', '+81', 'JP', 'jp.svg'),
('Jordan', '+962', 'JO', 'jo.svg'),
('Kazakhstan', '+7 7', 'KZ', 'kz.svg'),
('Kenya', '+254', 'KE', 'ke.svg'),
('Kiribati', '+686', 'KI', 'ki.svg'),
('Kuwait', '+965', 'KW', 'kw.svg'),
('Kyrgyzstan', '+996', 'KG', 'kg.svg'),
('Laos', '+856', 'LA', 'la.svg'),
('Latvia', '+371', 'LV', 'lv.svg'),
('Lebanon', '+961', 'LB', 'lb.svg'),
('Lesotho', '+266', 'LS', 'ls.svg'),
('Liberia', '+231', 'LR', 'lr.svg'),
('Libya', '+218', 'LY', 'ly.svg'),
('Liechtenstein', '+423', 'LI', 'li.svg'),
('Lithuania', '+370', 'LT', 'lt.svg'),
('Luxembourg', '+352', 'LU', 'lu.svg'),
('Macau', '+853', 'MO', 'mo.svg'),
('Macedonia', '+389', 'MK', 'mk.svg'),
('Madagascar', '+261', 'MG', 'mg.svg'),
('Malawi', '+265', 'MW', 'mw.svg'),
('Malaysia', '+60', 'MY', 'my.svg'),
('Maldives', '+960', 'MV', 'mv.svg'),
('Mali', '+223', 'ML', 'ml.svg'),
('Malta', '+356', 'MT', 'mt.svg'),
('Marshall Islands', '+692', 'MH', 'mh.svg'),
('Martinique', '+596', 'MQ', 'mq.svg'),
('Mauritania', '+222', 'MR', 'mr.svg'),
('Mauritius', '+230', 'MU', 'mu.svg'),
('Mayotte', '+262', 'YT', 'yt.svg'),
('Mexico', '+52', 'MX', 'mx.svg'),
('Micronesia', '+691', 'FM', 'fm.svg'),
('Moldova', '+373', 'MD', 'md.svg'),
('Monaco', '+377', 'MC', 'mc.svg'),
('Mongolia', '+976', 'MN', 'mn.svg'),
('Montenegro', '+382', 'ME', 'me.svg'),
('Montserrat', '+1664', 'MS', 'ms.svg'),
('Morocco', '+212', 'MA', 'ma.svg'),
('Myanmar', '+95', 'MM', 'mm.svg'),
('Namibia', '+264', 'NA', 'na.svg'),
('Nauru', '+674', 'NR', 'nr.svg'),
('Nepal', '+977', 'NP', 'np.svg'),
('Netherlands', '+31', 'NL', 'nl.svg'),
('Saint Kitts and Nevis', '+1', 'KN', 'kn.svg'),
('New Caledonia', '+687', 'NC', 'nc.svg'),
('New Zealand', '+64', 'NZ', 'nz.svg'),
('Nicaragua', '+505', 'NI', 'ni.svg'),
('Niger', '+227', 'NE', 'ne.svg'),
('Nigeria', '+234', 'NG', 'ng.svg'),
('Niue', '+683', 'NU', 'nu.svg'),
('Norfolk Island', '+672', 'NF', 'nf.svg'),
('North Korea', '+850', 'KP', 'kp.svg'),
('Northern Mariana Islands', '+1 670', 'MP', 'mp.svg'),
('Norway', '+47', 'NO', 'no.svg'),
('Oman', '+968', 'OM', 'om.svg'),
('Pakistan', '+92', 'PK', 'pk.svg'),
('Palau', '+680', 'PW', 'pw.svg'),
('Panama', '+507', 'PA', 'pa.svg'),
('Papua New Guinea', '+675', 'PG', 'pg.svg'),
('Paraguay', '+595', 'PY', 'py.svg'),
('Peru', '+51', 'PE', 'pe.svg'),
('Philippines', '+63', 'PH', 'ph.svg'),
('Poland', '+48', 'PL', 'pl.svg'),
('Portugal', '+351', 'PT', 'pt.svg'),
('Puerto Rico', '+1 787', 'PR', 'pr.svg'),
('Qatar', '+974', 'QA', 'qa.svg'),
('Reunion', '+262', 'RE', 're.svg'),
('Romania', '+40', 'RO', 'ro.svg'),
('Russia', '+7', 'RU', 'ru.svg'),
('Rwanda', '+250', 'RW', 'rw.svg'),
('Samoa', '+685', 'WS', 'ws.svg'),
('San Marino', '+378', 'SM', 'sm.svg'),
('Saudi Arabia', '+966', 'SA', 'sa.svg'),
('Senegal', '+221', 'SN', 'sn.svg'),
('Serbia', '+381', 'RS', 'rs.svg'),
('Seychelles', '+248', 'SC', 'sc.svg'),
('Sierra Leone', '+232', 'SL', 'sl.svg'),
('Singapore', '+65', 'SG', 'sg.svg'),
('Slovakia', '+421', 'SK', 'sk.svg'),
('Slovenia', '+386', 'SI', 'si.svg'),
('Solomon Islands', '+677', 'SB', 'sb.svg'),
('South Africa', '+27', 'ZA', 'za.svg'),
('South Georgia and the South Sandwich Islands', '+500', 'GS', 'gs.svg'),
('South Korea', '+82', 'KR', 'kr.svg'),
('Spain', '+34', 'ES', 'es.svg'),
('Sri Lanka', '+94', 'LK', 'lk.svg'),
('Sudan', '+249', 'SD', 'sd.svg'),
('Suriname', '+597', 'SR', 'sr.svg'),
('Swaziland', '+268', 'SZ', 'sz.svg'),
('Sweden', '+46', 'SE', 'se.svg'),
('Switzerland', '+41', 'CH', 'ch.svg'),
('Syria', '+963', 'SY', 'sy.svg'),
('Taiwan', '+886', 'TW', 'tw.svg'),
('Tajikistan', '+992', 'TJ', 'tj.svg'),
('Tanzania', '+255', 'TZ', 'tz.svg'),
('Thailand', '+66', 'TH', 'th.svg'),
('Timor Leste', '+670', 'TL', 'tl.svg'),
('Togo', '+228', 'TG', 'tg.svg'),
('Tokelau', '+690', 'TK', 'tk.svg'),
('Tonga', '+676', 'TO', 'to.svg'),
('Trinidad and Tobago', '+1 868', 'TT', 'tt.svg'),
('Tunisia', '+216', 'TN', 'tn.svg'),
('Turkey', '+90', 'TR', 'tr.svg'),
('Turkmenistan', '+993', 'TM', 'tm.svg'),
('Turks and Caicos Islands', '+1 649', 'TC', 'tc.svg'),
('Tuvalu', '+688', 'TV', 'tv.svg'),
('Uganda', '+256', 'UG', 'ug.svg'),
('Ukraine', '+380', 'UA', 'ua.svg'),
('United Arab Emirates', '+971', 'AE', 'ae.svg'),
('United Kingdom', '+44', 'GB', 'gb.svg'),
('United States', '+1', 'US', 'us.svg'),
('Uruguay', '+598', 'UY', 'uy.svg'),
('Uzbekistan', '+998', 'UZ', 'uz.svg'),
('Vanuatu', '+678', 'VU', 'vu.svg'),
('Venezuela', '+58', 'VE', 've.svg'),
('Vietnam', '+84', 'VN', 'vn.svg'),
('Wallis and Futuna', '+681', 'WF', 'wf.svg'),
('Yemen', '+967', 'YE', 'ye.svg'),
('Zambia', '+260', 'ZM', 'zm.svg'),
('Zimbabwe', '+263', 'ZW', 'zw.svg')
0

For those, who need it in German:

package at.ciit.apf.common.util;

import java.util.HashMap;
import java.util.Map;

public class CountryUtil {
private static Map<String,String> map = new HashMap<>();

static {
    initCountries();
}

public static String getCountryFromCountryCode(String countryCode){
    if (countryCode==null) return "";
    String result = map.get(countryCode.toUpperCase());
    if (result==null) result = "";
    return result;
}

private static void initCountries() {
    map.put("AF","Afghanistan");
    map.put("EG","Ägypten");
    map.put("AX","Ålandinseln");
    map.put("AL","Albanien");
    map.put("DZ","Algerien");
    map.put("AS","Amerikanisch Samoa");
    map.put("AD","Andorra");
    map.put("AO","Angola");
    map.put("AI","Anguilla");
    map.put("AQ","Antarktis");
    map.put("AG","Antigua und Barbuda");
    map.put("GQ","Äquatorialguinea");
    map.put("AR","Argentinien");
    map.put("AM","Armenien");
    map.put("AW","Aruba");
    map.put("AZ","Aserbaidschan");
    map.put("ET","Äthiopien");
    map.put("AU","Australien");
    map.put("BS","Bahamas");
    map.put("BH","Bahrain");
    map.put("BD","Bangladesch");
    map.put("BB","Barbados");
    map.put("BY","Belarus");
    map.put("BE","Belgien");
    map.put("BZ","Belize");
    map.put("BJ","Benin");
    map.put("BM","Bermuda");
    map.put("BT","Bhutan");
    map.put("BO","Bolivien");
    map.put("BQ","Bonaire, Sint Eustatius und Saba");
    map.put("BA","Bosnien und Herzegowina");
    map.put("BW","Botswana");
    map.put("BV","Bouvetinsel");
    map.put("BR","Brasilien");
    map.put("IO","Britisches Territorium im Indischen Ozean");
    map.put("BN","Brunei");
    map.put("BG","Bulgarien");
    map.put("BF","Burkina Faso");
    map.put("BI","Burundi");
    map.put("CL","Chile");
    map.put("CN","China");
    map.put("CK","Cookinseln");
    map.put("CR","Costa Rica");
    map.put("CW","Curaçao");
    map.put("DK","Dänemark");
    map.put("CD","Demokratische Republik Kongo");
    map.put("DE","Deutschland");
    map.put("DM","Dominica");
    map.put("DO","Dominikanische Republik");
    map.put("DJ","Dschibuti");
    map.put("EC","Ecuador");
    map.put("SV","El Salvador");
    map.put("CI","Elfenbeinküste");
    map.put("ER","Eritrea");
    map.put("EE","Estland");
    map.put("SZ","Eswatini");
    map.put("FK","Falklandinseln");
    map.put("FO","Färöer-Inseln");
    map.put("FJ","Fidschi");
    map.put("FI","Finnland");
    map.put("FR","Frankreich");
    map.put("GF","Französisch-Guayana");
    map.put("PF","Französisch-Polynesien");
    map.put("TF","Französische Süd- und Antarktisgebiete");
    map.put("GA","Gabun");
    map.put("GM","Gambia");
    map.put("GE","Georgien");
    map.put("GH","Ghana");
    map.put("GI","Gibraltar");
    map.put("GD","Grenada");
    map.put("GR","Griechenland");
    map.put("GL","Grönland");
    map.put("GP","Guadeloupe");
    map.put("GU","Guam");
    map.put("GT","Guatemala");
    map.put("GG","Guernsey");
    map.put("GN","Guinea");
    map.put("GW","Guinea-Bissau");
    map.put("GY","Guyana");
    map.put("HT","Haiti");
    map.put("HM","Heard und McDonaldinseln");
    map.put("HN","Honduras");
    map.put("HK","Hongkong");
    map.put("IN","Indien");
    map.put("ID","Indonesien");
    map.put("IM","Insel Man");
    map.put("IQ","Irak");
    map.put("IR","Iran");
    map.put("IE","Irland");
    map.put("IS","Island");
    map.put("IL","Israel");
    map.put("IT","Italien");
    map.put("JM","Jamaika");
    map.put("JP","Japan");
    map.put("YE","Jemen");
    map.put("JE","Jersey");
    map.put("JO","Jordanien");
    map.put("VG","Jungferninseln (UK)");
    map.put("VI","Jungferninseln (US)");
    map.put("KY","Kaimaninseln");
    map.put("KH","Kambodscha");
    map.put("CM","Kamerun");
    map.put("CA","Kanada");
    map.put("CV","Kap Verde");
    map.put("KZ","Kasachstan");
    map.put("QA","Katar");
    map.put("KE","Kenia");
    map.put("KG","Kirgisistan");
    map.put("KI","Kiribati");
    map.put("CC","Kokosinseln");
    map.put("CO","Kolumbien");
    map.put("KM","Komoren");
    map.put("XK","Kosovo");
    map.put("HR","Kroatien");
    map.put("CU","Kuba");
    map.put("KW","Kuwait");
    map.put("LA","Laos");
    map.put("LS","Lesotho");
    map.put("LV","Lettland");
    map.put("LB","Libanon");
    map.put("LR","Liberia");
    map.put("LY","Libyen");
    map.put("LI","Liechtenstein");
    map.put("LT","Litauen");
    map.put("LU","Luxemburg");
    map.put("MO","Macau");
    map.put("MG","Madagaskar");
    map.put("MW","Malawi");
    map.put("MY","Malaysia");
    map.put("MV","Malediven");
    map.put("ML","Mali");
    map.put("MT","Malta");
    map.put("MA","Marokko");
    map.put("MH","Marshallinseln");
    map.put("MQ","Martinique");
    map.put("MR","Mauretanien");
    map.put("MU","Mauritius");
    map.put("YT","Mayotte");
    map.put("MX","Mexiko");
    map.put("FM","Mikronesien");
    map.put("MD","Moldawien");
    map.put("MC","Monaco");
    map.put("MN","Mongolei");
    map.put("ME","Montenegro");
    map.put("MS","Montserrat");
    map.put("MZ","Mosambik");
    map.put("MM","Myanmar");
    map.put("NA","Namibia");
    map.put("NR","Nauru");
    map.put("NP","Nepal");
    map.put("NC","Neukaledonien");
    map.put("NZ","Neuseeland");
    map.put("NI","Nicaragua");
    map.put("NL","Niederlande");
    map.put("NE","Niger");
    map.put("NG","Nigeria");
    map.put("NU","Niue");
    map.put("KP","Nordkorea");
    map.put("MP","Nördliche Marianen");
    map.put("MK","Nordmazedonien");
    map.put("NF","Norfolkinsel");
    map.put("NO","Norwegen");
    map.put("OM","Oman");
    map.put("AT","Österreich");
    map.put("TL","Osttimor");
    map.put("PK","Pakistan");
    map.put("PS","Palästina");
    map.put("PW","Palau");
    map.put("PA","Panama");
    map.put("PG","Papua-Neuguinea");
    map.put("PY","Paraguay");
    map.put("PE","Peru");
    map.put("PH","Philippinen");
    map.put("PN","Pitcairninseln");
    map.put("PL","Polen");
    map.put("PT","Portugal");
    map.put("PR","Puerto Rico");
    map.put("CG","Republik Kongo");
    map.put("RE","Réunion");
    map.put("RW","Ruanda");
    map.put("RO","Rumänien");
    map.put("RU","Russland");
    map.put("MF","Saint Martin");
    map.put("SB","Salomonen");
    map.put("ZM","Sambia");
    map.put("WS","Samoa");
    map.put("SM","San Marino");
    map.put("BL","Sankt Bartholomäus");
    map.put("ST","São Tomé und Príncipe");
    map.put("SA","Saudi-Arabien");
    map.put("SE","Schweden");
    map.put("CH","Schweiz");
    map.put("SN","Senegal");
    map.put("RS","Serbien");
    map.put("SC","Seychellen");
    map.put("SL","Sierra Leone");
    map.put("ZW","Simbabwe");
    map.put("SG","Singapur");
    map.put("SX","Sint Maarten");
    map.put("SK","Slowakei");
    map.put("SI","Slowenien");
    map.put("SO","Somalia");
    map.put("ES","Spanien");
    map.put("LK","Sri Lanka");
    map.put("SH","St. Helena");
    map.put("KN","St. Kitts und Nevis");
    map.put("LC","St. Lucia");
    map.put("PM","St. Pierre und Miquelon");
    map.put("VC","St. Vincent und die Grenadinen");
    map.put("ZA","Südafrika");
    map.put("SD","Sudan");
    map.put("GS","Südgeorgien und die Südlichen Sandwichinseln");
    map.put("KR","Südkorea");
    map.put("SS","Südsudan");
    map.put("SR","Suriname");
    map.put("SJ","Svalbard und Jan Mayen");
    map.put("SY","Syrien");
    map.put("TJ","Tadschikistan");
    map.put("TW","Taiwan");
    map.put("TZ","Tansania");
    map.put("TH","Thailand");
    map.put("TG","Togo");
    map.put("TK","Tokelau");
    map.put("TO","Tonga");
    map.put("TT","Trinidad und Tobago");
    map.put("TD","Tschad");
    map.put("CZ","Tschechien");
    map.put("TN","Tunesien");
    map.put("TR","Türkei");
    map.put("TM","Turkmenistan");
    map.put("TC","Turks und Caicosinseln");
    map.put("TV","Tuvalu");
    map.put("UG","Uganda");
    map.put("UA","Ukraine");
    map.put("HU","Ungarn");
    map.put("UY","Uruguay");
    map.put("UZ","Usbekistan");
    map.put("VU","Vanuatu");
    map.put("VA","Vatikanstadt");
    map.put("VE","Venezuela");
    map.put("AE","Vereinigte Arabische Emirate");
    map.put("US","Vereinigte Staaten von Amerika");
    map.put("GB","Vereinigtes Königreich");
    map.put("VN","Vietnam");
    map.put("WF","Wallis und Futuna");
    map.put("CX","Weihnachtsinsel");
    map.put("EH","Westsahara");
    map.put("CF","Zentralafrikanische Republik");
    map.put("CY","Zypern");
}

}
Michael
  • 192
  • 1
  • 5
0

This is how to create sorted map containing english country name as key and ISO2 code as value:

static Map<String, String> countriesMap = Arrays.stream( Locale.getISOCountries() ).collect(
            Collectors.toMap( (String code)-> new Locale( "", code ).getDisplayCountry(Locale.ENGLISH),
                    Function.identity(),(o1, o2) -> o1, TreeMap::new ));

You can initiate it as statc fieled to avoid recalculation for every use.

radzimir
  • 1,178
  • 13
  • 10
0

You can use JCountry which is an open source library containing the ISO 3166-1 codes, and it's corresponding country name translations to different languages. It is a wrapper for the debian iso-codes info. It also contains the iso codes for languages (iso 639-2) and the corresponding language name translations.

Basically you can get a hash map of <"country Name" to "country info"> and look for it.

You can do it the other way around, by looking for a country info by using the alpha2 or alpha3 code. This library also has translations to country names but de default is english (also for the map suggested before).

Here is the repo in case you want to dig more: https://github.com/castmart/jcountry

JCountry jcountry = JCountry.getInstance();
CountryDB countryDB = jcountry.getCountriesDB();
// Get the countries DB hash maps <String, Country>
var dbByAlpha2 = countryDB.getCountriesMapByAlpha2();
var dbByAlpha3 = countryDB.getCountriesMapByAlpha3();
var dbByName = countryDB.getCountriesMapByName();

// Get Translations by language based locale 
Optional<ResourceBundle> bundle = countryDB.getCountriesTranslations(Locale.GERMAN);

// MX -> Mexiko
var translatedCountryName = bundle.get().getString(dbByAlpha2.get("MX").getName());

// Languages DB
LanguageDB languageDB = new LanguageDBImpl(true);
var dbByAlpha2 = languageDB.getLanguagesMapByAlpha2();

// Get Translations by language based locale 
Optional<ResourceBundle> bundle = languageDB.getLanguagesTranslations(Locale.GERMAN);

// Spanisch (Kastilisch)
var translatedCountryName = bundle.get().getString(dbByAlpha2.get("es").getName());
CastMart
  • 98
  • 5