Last active
May 7, 2018 12:29
-
-
Save guysmoilov/e57e8eaec5fbb497e2612c49fc85cd7f to your computer and use it in GitHub Desktop.
Java lexicographical comparator for lists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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