0

I want to generate a list of all countries in a sorted list. I tried this:

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

But for some reason the list is unsorted. What is the proper way to fort it?

Naghaveer R
  • 2,842
  • 4
  • 24
  • 49
Peter Penzov
  • 2,352
  • 100
  • 358
  • 675

1 Answers1

2

HashMap is unsorted, use LinkedHashMap:

This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

Just change

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

to:

Map<String, String> list = new LinkedHashMap<>();
xingbin
  • 25,716
  • 8
  • 51
  • 94