Java Sort List of Lists

后端 未结 2 508
挽巷
挽巷 2020-11-30 13:50

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

private List>         


        
2条回答
  •  借酒劲吻你
    2020-11-30 14:33

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

    class ListComparator> implements Comparator> {
    
      @Override
      public int compare(List o1, List 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> listOfLists = ...;
    
    Collections.sort(listOfLists, new ListComparator<>());
    

提交回复
热议问题