简体   繁体   中英

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() 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM