Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Java lexicographical comparator for lists
import java.util.Comparator;
import java.util.List;
* Compares {@link Comparable} list instances lexicographically.
* Assumes that the lists are not null, that they contain no null elements, and that they are optimized for random access!
* <p>
* Created by Tolstoyevsky on 08/02/2017.
* </p>
public class ListComparator<T extends Comparable<? super T>> implements Comparator<List<T>> {
public int compare(List<T> list1, List<T> list2) {
for (int i = 0; i < list1.size() && i < list2.size(); i++) {
T c1 = list1.get(i);
T c2 = list2.get(i);
int innerComparison = c1.compareTo(c2);
if (innerComparison != 0) {
return innerComparison;
// The lists start with the same prefix, only thing left to check is length ("aa" < "aaa")
return list1.size() - list2.size();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment