Sort ArrayList of Array in Java

Solution 1:

Start with Collections.sort, the one that takes a custom Comparator. You'll need to write a custom Comparator for this also.

For instance, assuming you want to rely on the natural ordering of Strings as defined in their compareTo method:

public static void main(String[] args) throws Exception {
        ArrayList<String[]> listOfStringArrays = new ArrayList<String[]>();
        listOfStringArrays.add(new String[] {"x","y","z"});
        listOfStringArrays.add(new String[] {"a","b","c"});
        listOfStringArrays.add(new String[] {"m","n","o"});
        Collections.sort(listOfStringArrays,new Comparator<String[]>() {
            public int compare(String[] strings, String[] otherStrings) {
                return strings[1].compareTo(otherStrings[1]);
            }
        });
        for (String[] sa : listOfStringArrays) {
            System.out.println(Arrays.toString(sa));
        }
        /* prints out 
          [a, b, c]
          [m, n, o]
          [x, y, z]
        */ 

    }

Solution 2:

You create a Comparator<String[]> like so:

new Comparator<String[]>() {
  public int compare(String[] first, String[] second) {
    return first[1].compareTo(second[1]);
  }
}

then pass it to Collections.sort().

You might want to do some checking if the second element is actually present in the array. You could also do a custom comparison if the standard String comparison isn't enough.

Solution 3:

You write a Comparator that compares two String[] by the correct child, and then you pass it to Collections.sort(List<T> list, Comparator<? super T> c).

Solution 4:

This is extremely easy to do with Java 8. Just write:

list.sort(Comparator.comparing(a -> a[1]));

For example, the following code:

List<String[]> list = Arrays.asList(
    new String[] { "abc", "abc", "abc", "abc", "abc", "abc", "abc" },
    new String[] { "xyz", "xyz", "xyz", "xyz", "xyz", "xyz", "xyz" },
    new String[] { "fgh", "fgh", "fgh", "fgh", "fgh", "fgh", "fgh" });

list.sort(Comparator.comparing(a -> a[1]));
list.stream().map(Arrays::toString).forEach(System.out::println);

Will yield the wanted result:

[abc, abc, abc, abc, abc, abc, abc]
[fgh, fgh, fgh, fgh, fgh, fgh, fgh]
[xyz, xyz, xyz, xyz, xyz, xyz, xyz]