Skip to content

Instantly share code, notes, and snippets.

@guysmoilov
Last active May 7, 2018 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guysmoilov/e57e8eaec5fbb497e2612c49fc85cd7f to your computer and use it in GitHub Desktop.
Save guysmoilov/e57e8eaec5fbb497e2612c49fc85cd7f to your computer and use it in GitHub Desktop.
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>> {
@Override
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