Vijay Kumar
Vijay Kumar

Reputation: 81

How to sort list of locale objects in list interface using comparator in java

I would like to sort Locale objects in list interface. below is the code i am using. List<Locale> list = LocaleUtils.availableLocaleList(); LocaleUtils.availableLocaleList() on calling this we are getting the list of available locales in java, localeutils is the class from org.apache.commons.lang.LocaleUtils.

I am trying to using the comparator interface below code.

            List<Locale> locale = LocaleUtils.availableLocaleList();
    Comparator<Locale> comparator = new Comparator<Locale>() {

        @Override
        public int compare(Locale o1, Locale o2) {
            return o1.toString().compareTo(o2.toString());
        }
    };

    Collections.sort(list, comparator);
    System.out.println(list);

I am able to print all the locales before sorting. But I am not able to sort the locale objects I am getting the below exception.

Could you please help me to sort it this issue.

any body could you please help me. Thanks and Regards Vijay

Upvotes: 3

Views: 1453

Answers (1)

Lukas Eichler
Lukas Eichler

Reputation: 5913

You are using an unmodifiable list. If you put the elements in a modifiable list it can be sorted. Otherwise you could your own sorting algorithm that put the elements in a new list. This approach could be faster. Try this instead:

List<Locale> localeList = new ArrayList<Locale>(list);
Collections.sort(localeList, comparator);

Upvotes: 4

Related Questions