java - 国家/地区排序列表
问题描述
我想在排序列表中生成所有国家的列表。我试过这个:
public Map<String, String> getCountryNameCodeList() {
String[] countryCodes = Locale.getISOCountries();
Arrays.sort(countryCodes);
Map<String, String> list = new HashMap<>();
for (String countryCode : countryCodes) {
Locale obj = new Locale("", countryCode);
list.put(obj.getDisplayCountry(), obj.getCountry());
}
return list;
}
但由于某种原因,该列表未排序。加固它的正确方法是什么?
解决方案
HashMap
未排序,使用LinkedHashMap
:
此实现与 HashMap 的不同之处在于它维护一个双向链表,该列表贯穿其所有条目。这个链表定义了迭代顺序,通常是键插入映射的顺序(插入顺序)。
只是改变
Map<String, String> list = new HashMap<>();
至:
Map<String, String> list = new LinkedHashMap<>();
推荐阅读
- javascript - 如何在反应中利用子组件中的状态值
- python - Python我如何在BeautifulSoup中提取具有相同类名的数据
- c++ - c++ - 如何将字符串中的所有大写字母转换为小写字母,反之亦然?
- reactjs - 在.map(Reactjs)中添加if条件后收到错误“期望赋值或函数调用,而是看到表达式”
- mysql - 在一个 SQL 查询中合并(合并)两个表中的两列
- regex - PCRE Regexp - 仅匹配一对方括号
- c++ - 新分配指向函数的指针是否合法?
- api - Sonarqube API 调用错误响应
- vue.js - vue如何将文件发送到后端
- c# - 无法使用 amqmdnetstd.dll 连接到 MQ