是否有 ISO 3166-1 国家代码的开源 Java 枚举

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/139867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:47:29  来源:igfitidea点击:

Is there an open source java enum of ISO 3166-1 country codes

javainternationalizationcountry-codesiso-3166

提问by Jason Jenkins

Does anyone know of a freely available java 1.5 package that provides a list of ISO 3166-1 country codes as a enum or EnumMap? Specifically I need the "ISO 3166-1-alpha-2 code elements", i.e. the 2 character country code like "us", "uk", "de", etc. Creating one is simple enough (although tedious), but if there's a standard one already out there in apache land or the like it would save a little time.

有谁知道一个免费提供的 java 1.5 包,它提供了一个 ISO 3166-1 国家代码列表作为枚举或 EnumMap?具体来说,我需要“ISO 3166-1-alpha-2 代码元素”,即 2 个字符的国家/地区代码,如“us”、“uk”、“de”等。创建一个很简单(虽然很乏味),但是如果在 apache 土地或类似的地方已经有一个标准的,它会节省一点时间。

回答by McDowell

This code gets 242 countries in Sun Java 6:

此代码在 Sun Java 6 中获取 242 个国家/地区:

String[] countryCodes = Locale.getISOCountries();

Though the ISO websiteclaims there are 249 ISO 3166-1-alpha-2 code elements, though the javadoclinks to the same information.

尽管ISO 网站声称有 249 个ISO 3166-1-alpha-2 代码元素,但javadoc链接到相同的信息。

回答by Christophe Desguez

There is an easy way to generate this enum with the language name. Execute this code to generate the list of enum fields to paste :

有一种简单的方法可以使用语言名称生成此枚举。执行此代码以生成要粘贴的枚举字段列表:

 /**
  * This is the code used to generate the enum content
  */
 public static void main(String[] args) {
  String[] codes = java.util.Locale.getISOLanguages();
  for (String isoCode: codes) {
   Locale locale = new Locale(isoCode);
   System.out.println(isoCode.toUpperCase() + "(\"" + locale.getDisplayLanguage(locale) + "\"),");
  }
 }

回答by Bozho

Here's how I generated an enum with country code + country name:

下面是我如何生成一个带有国家代码 + 国家名称的枚举:

package countryenum;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

public class CountryEnumGenerator {
    public static void main(String[] args) {
        String[] countryCodes = Locale.getISOCountries();
        List<Country> list = new ArrayList<Country>(countryCodes.length);

        for (String cc : countryCodes) {
            list.add(new Country(cc.toUpperCase(), new Locale("", cc).getDisplayCountry()));
        }

        Collections.sort(list);

        for (Country c : list) {
            System.out.println("/**" + c.getName() + "*/");
            System.out.println(c.getCode() + "(\"" + c.getName() + "\"),");
        }

    }
}

class Country implements Comparable<Country> {
    private String code;
    private String name;

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

    public String getCode() {
        return code;
    }


    public void setCode(String code) {
        this.code = code;
    }


    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }


    @Override
    public int compareTo(Country o) {
        return this.name.compareTo(o.name);
    }
}

回答by bruno.braga

This still does not answer the question. I was also looking for a kind of enumerator for this, and did not find anything. Some examples using hashtable here, but represent the same as the built-in get

这仍然没有回答问题。我也在为此寻找一种枚举器,但没有找到任何东西。此处使用哈希表的一些示例,但表示与内置 get 相同

I would go for a different approach. So I created a script in python to automatically generate the list in Java:

我会采用不同的方法。所以我在python中创建了一个脚本来自动生成Java中的列表:

#!/usr/bin/python
f = open("data.txt", 'r')
data = []
cc = {}

for l in f:
    t = l.split('\t')
    cc = { 'code': str(t[0]).strip(), 
           'name': str(t[1]).strip()
    }
    data.append(cc)
f.close()

for c in data:
    print """
/**
 * Defines the <a href="http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2">ISO_3166-1_alpha-2</a> 
 * for <b><i>%(name)s</i></b>.
 * <p>
 * This constant holds the value of <b>{@value}</b>.
 *
 * @since 1.0
 *
 */
 public static final String %(code)s = \"%(code)s\";""" % c

where the data.txt file is a simple copy&paste from Wikipedia table (just remove all extra lines, making sure you have a country code and country name per line).

其中 data.txt 文件是从 Wikipedia 表中简单的复制和粘贴(只需删除所有多余的行,确保每行都有一个国家/地区代码和国家/地区名称)。

Then just place this into your static class:

然后把它放到你的静态类中:

/**
 * Holds <a href="http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2">ISO_3166-1_alpha-2</a>
 * constant values for all countries. 
 * 
 * @since 1.0
 * 
 * </p>
 */
public class CountryCode {

    /**
     * Constructor defined as <code>private</code> purposefully to ensure this 
     * class is only used to access its static properties and/or methods.  
     */
    private CountryCode() { }

    /**
     * Defines the <a href="http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2">ISO_3166-1_alpha-2</a> 
     * for <b><i>Andorra</i></b>.
     * <p>
     * This constant holds the value of <b>{@value}</b>.
     *
     * @since 1.0
     *
     */
     public static final String AD = "AD";

         //
         // and the list goes on! ...
         //
}

回答by Takahiko Kawasaki

Now an implementation of country code (ISO 3166-1alpha-2/alpha-3/numeric) list as Java enum is available at GitHub under Apache License version 2.0.

现在,国家代码 ( ISO 3166-1 alpha-2/ alpha-3/ numeric) 列表作为 Java 枚举的实现可在 Apache 许可证版本 2.0 下在 GitHub 上获得。

Example:

例子:

CountryCode cc = CountryCode.getByCode("JP");

System.out.println("Country name = " + cc.getName());                // "Japan"
System.out.println("ISO 3166-1 alpha-2 code = " + cc.getAlpha2());   // "JP"
System.out.println("ISO 3166-1 alpha-3 code = " + cc.getAlpha3());   // "JPN"
System.out.println("ISO 3166-1 numeric code = " + cc.getNumeric());  // 392


Last Edit2016-Jun-09

最后编辑2016-Jun-09

CountryCode enum was packaged into com.neovisionaries.i18n with other Java enums, LanguageCode (ISO 639-1), LanguageAlpha3Code (ISO 639-2), LocaleCode, ScriptCode (ISO 15924) and CurrencyCode (ISO 4217) and registered into the Maven Central Repository.

CountryCode 枚举与其他 Java 枚举、LanguageCode ( ISO 639-1)、LanguageAlpha3Code ( ISO 639-2)、LocaleCode、ScriptCode ( ISO 15924) 和 CurrencyCode ( ISO 4217)一起打包到 com.neovisionaries.i18n并注册到 Maven Central存储库。

Maven

马文

<dependency>
  <groupId>com.neovisionaries</groupId>
  <artifactId>nv-i18n</artifactId>
  <version>1.22</version>
</dependency>

Gradle

摇篮

dependencies {
  compile 'com.neovisionaries:nv-i18n:1.22'
}

GitHub

GitHub

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

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

Javadoc

Javadoc

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

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

OSGi

操作系统

Bundle-SymbolicName: com.neovisionaries.i18n
Export-Package: com.neovisionaries.i18n;version="1.22.0"

回答by george_h

I didn't know about this question till I had just recently open-sourced my Java enum for exactly this purpose! Amazing coincidence!

我不知道这个问题,直到我最近刚刚为此目的开源了我的 Java 枚举!惊人的巧合!

I put the whole source code on my blog with BSD caluse 3 license so I don't think anyone would have any beefs about it.

我使用 BSD caluse 3 许可证将整个源代码放在我的博客上,所以我认为没有人会对此有任何异议。

Can be found here. https://subversivebytes.wordpress.com/2013/10/07/java-iso-3166-java-enum/

可以在这里找到。 https://subversivebytes.wordpress.com/2013/10/07/java-iso-3166-java-enum/

Hope it is useful and eases development pains.

希望它有用并减轻开发的痛苦。

回答by sskular

If you are already going to rely on Java locale, then I suggest using a simple HashMap instead of creating new classes for countries etc.

如果您已经打算依赖 Java 语言环境,那么我建议使用简单的 HashMap 而不是为国家/地区等创建新类。

Here's how I would use it if I were to rely on the Java Localization only:

如果我仅依赖 Java 本地化,我将如何使用它:

private HashMap<String, String> countries = new HashMap<String, String>();
String[] countryCodes = Locale.getISOCountries();

for (String cc : countryCodes) {
    // country name , country code map
    countries.put(new Locale("", cc).getDisplayCountry(), cc.toUpperCase());
}

After you fill the map, you can get the ISO code from the country name whenever you need it. Or you can make it a ISO code to Country name map as well, just modify the 'put' method accordingly.

填写地图后,您可以在需要时从国家/地区名称中获取 ISO 代码。或者您也可以将其设为国家名称映射的 ISO 代码,只需相应地修改 'put' 方法。

回答by Ben Dowling

Not a java enum, but a JSON version of this is available at http://country.io/names.json

不是 java 枚举,而是http://country.io/names.json提供的 JSON 版本

回答by abdielou

If anyone is already using the Amazon AWS SDK it includes com.amazonaws.services.route53domains.model.CountryCode. I know this is not ideal but it's an alternative if you already use the AWS SDK. For most cases I would use Takahiko's nv-i18nsince, as he mentions, it implements ISO 3166-1.

如果有人已经在使用 Amazon AWS 开发工具包,它会包含com.amazonaws.services.route53domains.model.CountryCode. 我知道这并不理想,但如果您已经使用 AWS 开发工具包,它是一种替代方法。在大多数情况下,我会使用 Takahiko 的,nv-i18n因为正如他所提到的,它实现了 ISO 3166-1。

回答by Hervian

I have created an enum, which you address by the english country name. See country-util.
On each enum you can call getLocale()to get the Java Locale.

我创建了一个枚举,您可以使用英文国家/地区名称进行寻址。请参阅country-util
在每个枚举上,您可以调用getLocale()以获取 Java 语言环境。

From the Locale you can get all the information you are used to, fx the ISO-3166-1 two letter country code.

从区域设置中,您可以获得您习惯的所有信息,例如 ISO-3166-1 两个字母的国家/地区代码。

public enum Country{

    ANDORRA(new Locale("AD")),
    AFGHANISTAN(new Locale("AF")),
    ANTIGUA_AND_BARBUDA(new Locale("AG")),
    ANGUILLA(new Locale("AI")),
    //etc
    ZAMBIA(new Locale("ZM")),
    ZIMBABWE(new Locale("ZW"));

    private Locale locale;

    private Country(Locale locale){
        this.locale = locale;
    }

    public Locale getLocale(){
        return locale;
    }

Pro:

亲:

  • Light weight
  • Maps to Java Locales
  • Addressable by full country name
  • Enum values are not hardcoded, but generated by a call to Locale.getISOCountries(). That is: Simply recompile the project against the newest java version to get any changes made to the list of countries reflected in the enum.
  • 轻的
  • 映射到 Java 语言环境
  • 可按国家全名寻址
  • 枚举值不是硬编码的,而是通过调用 Locale.getISOCountries() 生成的。即:只需根据最新的 Java 版本重新编译项目,即可获取对枚举中反映的国家/地区列表所做的任何更改。

Con:

骗局:

  • Not in Maven repository
  • Most likely simpler / less expressive than the other solutions, which I don't know.
  • Created for my own needs / not as such maintained. - You should probably clone the repo.
  • 不在 Maven 存储库中
  • 与我不知道的其他解决方案相比,很可能更简单/缺乏表现力。
  • 为我自己的需要而创建/不是这样维护的。- 你应该克隆 repo。