Java Sort List of Lists

后端 未结 2 491
挽巷
挽巷 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:15

    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());
    
    0 讨论(0)
  • 2020-11-30 14:33

    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<>());
    
    0 讨论(0)
提交回复
热议问题