首页 > 解决方案 > 国家/地区排序列表

问题描述

我想在排序列表中生成所有国家的列表。我试过这个:

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;
    }

但由于某种原因,该列表未排序。加固它的正确方法是什么?

标签: java

解决方案


HashMap未排序,使用LinkedHashMap

此实现与 HashMap 的不同之处在于它维护一个双向链表,该列表贯穿其所有条目。这个链表定义了迭代顺序,通常是键插入映射的顺序(插入顺序)。

只是改变

Map<String, String> list = new HashMap<>();

至:

Map<String, String> list = new LinkedHashMap<>();

推荐阅读