Last active
September 30, 2018 15:48
-
-
Save YuyaAizawa/0f17c51cda17f37603296231126f610d to your computer and use it in GitHub Desktop.
SortedSetComparatorのComparatorを作る
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
public class IterableComparator { | |
public static <T> Comparator<Iterable<T>> iterableComparator(Comparator<? super T> elementComparator) { | |
return (l1, l2) -> { | |
Iterator<T> i1 = l1.iterator(); | |
Iterator<T> i2 = l2.iterator(); | |
while(i1.hasNext() && i2.hasNext()) { | |
T t1 = i1.next(); | |
T t2 = i2.next(); | |
int c = elementComparator.compare(t1, t2); | |
if(c != 0) { | |
return c; | |
} | |
} | |
if(i1.hasNext()) { | |
return 1; | |
} | |
if(i2.hasNext()) { | |
return -1; | |
} | |
return 0; | |
}; | |
} | |
private static String cmpToString(int i) { | |
return i < 0 ? "<" : | |
i > 0 ? ">" : | |
"="; | |
} | |
public static void main(String[] args) { | |
SortedSet<Integer> s1 = new TreeSet<>(Set.of(1, 2, 4)); | |
SortedSet<Integer> s2 = new TreeSet<>(Set.of(1, 3, 4)); | |
SortedSet<Integer> s3 = new TreeSet<>(Set.of(1, 2)); | |
Comparator<Iterable<Integer>> cmp = iterableComparator(Comparator.naturalOrder()); | |
System.out.printf("s1 %s s1%n", cmpToString(cmp.compare(s1, s1))); | |
System.out.printf("s1 %s s2%n", cmpToString(cmp.compare(s1, s2))); | |
System.out.printf("s1 %s s3%n", cmpToString(cmp.compare(s1, s3))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment