Java如何获取国家名称列表?
使用下面的代码,您可以通过使用Java中的locale类实现获得国家名称及其ISO代码的列表。
package org.nhooo.example.util;
import java.text.Collator;
import java.util.*;
public class CountryList {
public static void main(String[] args) {
// 用来存储我们国家对象的集合
List<Country> countries = new ArrayList<Country>();
// 获取ISO国家/地区,创建“国家/地区”对象,然后
// 存储在集合中。
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));
}
}
// 按名称对国家/地区排序,然后显示内容
// 国家集合对象。
Collections.sort(countries, new CountryComparator());
for (Country country : countries) {
System.out.println(country);
}
}
/**
* Country pojo class.
*/
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();
}
}
/**
* CountryComparator class.
*/
private static class CountryComparator implements Comparator<Country> {
private Comparator<Object> comparator;
CountryComparator() {
comparator = Collator.getInstance();
}
public int compare(Country c1, Country c2) {
return comparator.compare(c1.name, c2.name);
}
}
}以下是我们列出的国家名单: