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,890
  • 4
  • 30
  • 52
Peter Penzov
  • 1,126
  • 134
  • 430
  • 808

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
  • 27,410
  • 9
  • 53
  • 103