javalistsorting

Java Sort List of Lists


How would I sort a list of lists in Java in lexicographical order using Collections.sort() or another sorting method?

private List<List<Integer>> possiblePoles = setPoles();    
System.out.println(possiblePoles)
[[1, 3, 5], [1, 2, 3]]

Solution

  • 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<>());