Reputation: 119
i want to sort ArrayList of Arraylist of Integer, and their lengths are different
i try the codes here sort an arraylist of arraylist of integers
it's worked but its priority in order of lengths first not values
for example:
2, 2 , 2, 3
2, 2, 3, 4
2, 2, 90
its output will be like this:
2, 2, 90
2, 2, 2, 3
2, 2, 3, 4
While the order I want:
2, 2, 2, 3
2, 2, 3, 4
2, 2, 90
can anyone help me to solve it?
Upvotes: 1
Views: 84
Reputation: 171
You can do it in two steps:
Sort arrays from the min to max values with the help of forEach(Collections::sort)
method.
Make a comparison of the arrays and arrange them in specific order.
List<List<Integer>> listOLists = Arrays.asList(
Arrays.asList(2, 90, 2),
Arrays.asList(3, 2, 4, 2),
Arrays.asList(2, 2, 3, 2));
//first step:
listOLists.forEach(Collections::sort);
//second step:
Collections.sort(listOLists, (l1, l2) -> {
for (int i = 0; i < listOLists.size(); i++) {
if (l1.get(i) != l2.get(i)) {
return l1.get(i) - l2.get(i);
}
}
return l1.get(0).compareTo(l2.get(0));
});
System.out.println(listOLists);
As a result you'll get:
[[2, 2, 2, 3], [2, 2, 3, 4], [2, 2, 90]]
Upvotes: 0
Reputation: 320
The code you are looking at only compares the first number in each list, so the order they end up in isn't actually by size; it's arbitrary.
The key is this part
public int compare(List<Integer> o1, List<Integer> o2) {
return o1.get(0).compareTo(o2.get(0));
}
You need something like
public int compare(List<Integer> o1, List<Integer> o2) {
for (int i = 0; i < o1.size(); i++) {
if (o1.get(i).compareTo(o2.get(i)) != 0) {
return o1.get(i).compareTo(o2.get(i));
}
}
}
I have left this incomplete since I assume this is supposed to be educational for you and there's nothing to be accomplished if I give you the whole answer. The code snipped I've written here will only properly compare lists of the same length. If the second list is longer extra values will be ignored and if the first list is longer it will error out. I will leave it as an exercise to you to resolve those issues. :-)
Upvotes: 2