How would I sort a list of lists in Java in lexicographical order using Collections.sort() or another sorting method?
private List>
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());
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<>());