java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to get a list of country names?

Using the code below you can get a list of country names and its ISO code by using the locale class implementation in Java.

package com.javacoderanch.example.util;

import java.util.*;
import java.text.Collator;

public class CountryList {
    public static void main(String[] args) {
        //
        // A collection to store our country object
        //
        List<Country> countries = new ArrayList<Country>();

        //
        // Get ISO countries, create Country object and
        // store in the collection.
        //
        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();

            if (!"".equals(iso) && !"".equals(code)
                    && !"".equals(name)) {
                countries.add(new Country(iso, code, name));
            }
        }

        //
        // Sort the country by their name and then display the content
        // of countries collection object.
        //
        Collections.sort(countries, new CountryComparator());

        for (Country country : countries) {
            System.out.println(country);
        }
    }

    static class Country {
        private String iso;
        private String code;
        private String name;

        Country(String iso, String code, String name) {
            this.iso = iso;
            this.code = code;
            this.name = name;
        }

        public String toString() {
            return iso + " - " + code + " - " + name.toUpperCase();
        }
    }

    static class CountryComparator implements Comparator {
        private Comparator comparator;

        CountryComparator() {
            comparator = Collator.getInstance();
        }

        @SuppressWarnings("unchecked")
        public int compare(Object o1, Object o2) {
            Country c1 = (Country) o1;
            Country c2 = (Country) o2;

            return comparator.compare(c1.name, c2.name);
        }
    }
}

Here are some of the list of countries we got:

...
...
GNQ - GQ - EQUATORIAL GUINEA
ERI - ER - ERITREA
EST - EE - ESTONIA
ETH - ET - ETHIOPIA
FLK - FK - FALKLAND ISLANDS
FRO - FO - FAROE ISLANDS
FJI - FJ - FIJI
FIN - FI - FINLAND
FRA - FR - FRANCE
GUF - GF - FRENCH GUIANA
PYF - PF - FRENCH POLYNESIA
...
...