Java 排序列表列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35761864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Sort List of Lists
提问by MartinS
How would I sort a list of lists in Java in lexicographical order using Collections.sort() or another sorting method?
如何使用 Collections.sort() 或其他排序方法按字典顺序对 Java 中的列表列表进行排序?
private List<List<Integer>> possiblePoles = setPoles();
System.out.println(possiblePoles)
[[1, 3, 5], [1, 2, 3]]
回答by MartinS
You will have to implement your own Comparator
class and pass in an instance to Collections.sort()
您必须实现自己的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());
}
}
Then sorting is easy
然后排序很容易
List<List<Integer>> listOfLists = ...;
Collections.sort(listOfLists, new ListComparator<>());
回答by Joby Wilson Mathews
Improved MartinS answer using Java 8 stream API
使用 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());