如何使用Collections.sort()或其他排序方法按字典顺序对Java列表进行排序?
private List<List<Integer>> possiblePoles = setPoles();
System.out.println(possiblePoles)
[[1, 3, 5], [1, 2, 3]]
Run Code Online (Sandbox Code Playgroud)
Mar*_*inS 14
您将必须实现自己的Comparator类并将实例传递给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());
}
}
Run Code Online (Sandbox Code Playgroud)
然后排序很容易
List<List<Integer>> listOfLists = ...;
Collections.sort(listOfLists, new ListComparator<>());
Run Code Online (Sandbox Code Playgroud)
使用 Java 8 流 API 改进 MartinS 答案
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());
Run Code Online (Sandbox Code Playgroud)