简体   繁体   English

如何按字母顺序对列表列表的第一个元素进行排序?

[英]How to sort the first elements of List of Lists in alphabetical order?

First of all what i would like the program to do is sort the lists by the first element of each list in alphabetical order. 首先,我希望程序要按字母顺序按列表的第一个元素对列表进行排序。 And then sort them back into its original order. 然后将它们重新排序为原始顺序。 Code below. 代码如下。

ArrayList<ArrayList<String>> mylist = new ArrayList<ArrayList<String>>();
    List<String> List1 = new ArrayList<String>();
    List<String> List2 = new ArrayList<String>();
    List<String> List3 = new ArrayList<String>();
    List1.add("A");
    List2.add("B");
    List3.add("A");
    List1.add("C");
    List2.add("D");
    List3.add("E"); 
    mylist.add((ArrayList<String>) List1);
    mylist.add((ArrayList<String>) List2);
    mylist.add((ArrayList<String>) List3);
    System.out.println(mylist.toString());

The Print at the minute is: 分钟打印是:

[[A, C], [B, D], [A, E]] [[A,C],[B,D],[A,E]]

I would like to sort them so the result is like: 我想对它们进行排序,结果如下:

[[A, C], [A, E], [B, D]] [[A,C],[A,E],[B,D]]

and then be able to sort them back into its original form: 然后能够将它们排序回原始形式:

[[A, C], [B, D], [A, E]] [[A,C],[B,D],[A,E]]

You can sort the list using a custom Comparator . 您可以使用自定义Comparator对列表进行排序。 If you are using Java 8 you can do it like this: 如果您使用的是Java 8,可以这样做:

mylist.sort((l1, l2) -> l1.get(0).compareTo(l2.get(0)));

Note that this will modify the original list, though, and there is no way to reverse the sort. 请注意,这将修改原始列表,但无法撤消排序。 Instead, you should create a copy and sort the copy. 相反,您应该创建副本并对副本进行排序。

For example: 例如:

List<List<String>> listToSort = new ArrayList<>(mylist);
listToSort.sort((l1, l2) -> l1.get(0).compareTo(l2.get(0)));
System.out.println(listToSort);

Output: 输出:

[[A, C], [A, E], [B, D]]

Note: 注意:

If you are using Java 7 and below, you should use Collections.sort() and create an explicit Comparator . 如果您使用的是Java 7及更低版本,则应使用Collections.sort()并创建一个显式的Comparator

To sort by alphabetical order of the first item of each list, implement a custom Comparator: 要按每个列表的第一项的字母顺序排序,请实现自定义比较器:

    Collections.sort(mylist, new Comparator<ArrayList<String>>(){

        @Override
        public int compare(ArrayList<String> arg0, ArrayList<String> arg1) {
            return arg0.get(0).compareTo(arg1.get(0));
        }

    });

You cannot reverse the order of this sort unless there is a particular algorithm you can use sort the element's original order. 除非有特定的算法可以使用对元素的原始顺序进行排序,否则不能颠倒此类的顺序。 This being said, to maintain the original order just create a copy of the List and sort either the original (or copied), which will leave you with a sorted and unsorted copy of the List. 这就是说,为了维护原始顺序,只需创建List的副本并对原始(或复制)进行排序,这将为您提供List的排序和未排序副本。

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

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