Java Sort List of Lists

Improved MartinS answer using Java 8 stream API

possiblePoles = possiblePoles.stream().sorted((o1,o2) -> {
             for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) {
                  int c = o1.get(i).compareTo(o2.get(i));
                  if (c != 0) {
                    return c;
                  }
                }
                return Integer.compare(o1.size(), o2.size());
         }).collect(Collectors.toList());

You will have to implement your own Comparator class and pass in an instance to Collections.sort()

class ListComparator<T extends Comparable<T>> implements Comparator<List<T>> {

  @Override
  public int compare(List<T> o1, List<T> o2) {
    for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) {
      int c = o1.get(i).compareTo(o2.get(i));
      if (c != 0) {
        return c;
      }
    }
    return Integer.compare(o1.size(), o2.size());
  }

}

Then sorting is easy

List<List<Integer>> listOfLists = ...;

Collections.sort(listOfLists, new ListComparator<>());

For this example [[1, 3], [1, 2]], if you want to sort the list by both elements you can use sorted from Java 8 manually implemented the comparator method, validating all cases like the following example:

List<List<Integer>> result = contests.stream().sorted((o1, o2) -> {
        if (o1.get(1) > o2.get(1) ||
            (o1.get(1).equals(o2.get(1)) && o1.get(0) > o2.get(0))) {
            return -1;
        } else if (o1.get(1) < o2.get(1) ||
            (o1.get(1).equals(o2.get(1)) && o1.get(0) < o2.get(0))) {
            return 1;
        }
        return 0;
    }).collect(Collectors.toList());

OR

contests.sort((o1, o2) -> {
                if (o1.get(1) > o2.get(1) ||
                    (o1.get(1).equals(o2.get(1)) && o1.get(0) > o2.get(0))) {
                    return -1;
                } else if (o1.get(1) < o2.get(1) ||
                    (o1.get(1).equals(o2.get(1)) && o1.get(0) < o2.get(0))) {
                    return 1;
                }
                return 0;
            });

Tags:

Java

Sorting

List