Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort the first elements of List of Lists in alphabetical order?

Tags:

java

list

sorting

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]]

like image 673
Tim Daiber Avatar asked Apr 02 '15 16:04

Tim Daiber


1 Answers

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.

like image 63
Anderson Vieira Avatar answered Oct 27 '22 00:10

Anderson Vieira