Reputation: 358
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]]
I would like to sort them so the result is like:
[[A, C], [A, E], [B, D]]
and then be able to sort them back into its original form:
[[A, C], [B, D], [A, E]]
Upvotes: 5
Views: 11867
Reputation: 9049
You can sort the list using a custom Comparator
. If you are using Java 8 you can do it like this:
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
.
Upvotes: 11
Reputation: 8348
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.
Upvotes: 0