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]]
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With