简体   繁体   中英

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]]

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

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

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;
            });
  possiblePoles.sort((l1, l2) -> {
        int minLength = Math.min(l1.size(), l2.size());
        for (int i = 0; i < minLength; i++) {
            int lexicographicalPosition = l1.get(i).compareTo(l2.get(i));
            if (lexicographicalPosition != 0) {
                return lexicographicalPosition;
            }
        }
        return Integer.compare(l1.size(), l2.size());
    });

Same logic with java 8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM