简体   繁体   English

Java中词典顺序的整数ArrayList的ArrayList

[英]ArrayList of ArrayList of Integers in lexicographic order in Java

I have an ArrayList<ArrayList<Integer>> and I want to sort it so I will have all the lists in lexicographic order. 我有一个ArrayList<ArrayList<Integer>> ,我想对它进行排序,所以我将按字典顺序排列所有列表。

For example: 例如:

The list before sorting (commas separate one list from other): 2 6 8, 1 3 6, 1 2 8 排序前的列表(逗号将一个列表与其他列表分开):2 6 8,1 3 6,1 2 8

What i want to get after sorting: 1 2 8, 1 3 6, 2 6 8 排序后我想得到的:1 2 8,1 3 6,2 6 8

I saw that I can use Collections.sort but saw it only for comparing a value at a single index only: 我看到我可以使用Collections.sort但只看到它仅用于比较单个索引的值:

Collections.sort(lists, new Comparator<ArrayList<Integer>>(){
    public int compare(ArrayList<Integer> list1, ArrayList<Integer> list2){
        return list1.get(0).compareTo(list2.get(0));
    }
});

But with that my result will be wrong (1 3 6, 1 2 8, 2 6 8). 但由此我的结果将是错误的(1 3 6,1 2 8,2 6 8)。

Is it possible to use something like this structure to compare not one value but all the them in the lists? 是否可以使用类似这种结构的东西来比较列表中的所有值而不是一个值? All lists have the same size. 所有列表都具有相同的大小。

Just iterate over both collections in the Comparator : (This doesn't check for same lengths, you might want to add it) 只需迭代Comparator两个集合:(这不会检查相同的长度,您可能想要添加它)

Collections.sort(lists, new Comparator<ArrayList<Integer>>(){
    public int compare(ArrayList<Integer> list1, ArrayList<Integer> list2){
        int result = 0;
        for (int i = 0; i <= list1.size() - 1 && result == 0; i++) 
        {
            result = list1.get(i).compareTo(list2.get(i));
        }
        return result;
    }
});

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

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