Best way to store Country codes, names, and Continent in Java

Click Upvote picture Click Upvote · Apr 3, 2009 · Viewed 17.9k times · Source

I want to have a List or Array of some sort, storing this information about each country:

  • 2 letter code
  • Country name such as Brazil
  • Continent/region of the world such as Eastern Europe, North America, etc.

I will classify each country into the region/continent manually (but if there exists a way to do this automatically, do let me know). This question is about how to store and access the countries. For example, I want to be able to retrieve all the countries in North America.

I don't want to use local text files or such because this project will be converted to javascript using Google Web Toolkit. But storing in an Enum or another resource file of some sort, keeping it separate from the rest of the code, is what I'm really after.

Answer

Michael Borgwardt picture Michael Borgwardt · Apr 3, 2009

Just make an enum called Country. Java enums can have properties, so there's your country code and name. For the continent, you pobably want another enum.

public enum Continent
{
    AFRICA, ANTARCTICA, ASIA, AUSTRALIA, EUROPE, NORTH_AMERICA, SOUTH_AMERICA
}

public enum Country
{
    ALBANIA("AL", "Albania", Continent.EUROPE),
    ANDORRA("AN", "Andorra", Continent.EUROPE),
    ...

    private String code;
    private String name;
    private Continent continent;

    // get methods go here    

    private Country(String code, String name, Continent continent)
    {
        this.code = code;
        this.name = name;
        this.continent = continent;
    }
}

As for storing and access, one Map for each of the fields you'll be searching for, keyed on that that field, would be the standard solution. Since you have multiple values for the continent, you'll either have to use a Map<?, List<Country>>, or a Multimap implementation e.g. from Apache commons.