简体   繁体   English

如何使用Java中的比较器在列表界面中对语言环境对象列表进行排序

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

I would like to sort Locale objects in list interface. 我想在列表界面中对Locale对象进行排序。 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 . List<Locale> list = LocaleUtils.availableLocaleList(); LocaleUtils.availableLocaleList()在调用它时,我们正在获取Java中可用语言环境的列表, localeutilsorg.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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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