Halep
Halep

Reputation: 93

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.

For example:

The list before sorting (commas separate one list from other): 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

I saw that I can use Collections.sort but saw it only for comparing a value at a single index only:

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

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.

Upvotes: 2

Views: 1252

Answers (1)

Mat
Mat

Reputation: 1500

Just iterate over both collections in the Comparator: (This doesn't check for same lengths, you might want to add it)

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

Upvotes: 5

Related Questions