import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
class Comparators {
public static T max(Collection extends T> coll, Comparator super T> cmp) {
T candidate = coll.iterator().next();
for (T elt : coll) {
if (cmp.compare(candidate, elt) < 0) {
candidate = elt;
}
}
return candidate;
}
public static > T max(Collection extends T> coll) {
return max(coll, Comparators. naturalOrder());
}
public static T min(Collection extends T> coll, Comparator super T> cmp) {
return max(coll, reverseOrder(cmp));
}
public static > T min(Collection extends T> coll) {
return max(coll, Comparators. reverseOrder());
}
public static > Comparator naturalOrder() {
return new Comparator() {
public int compare(T o1, T o2) {
return o1.compareTo(o2);
}
};
}
public static Comparator reverseOrder(final Comparator cmp) {
return new Comparator() {
public int compare(T o1, T o2) {
return cmp.compare(o2, o1);
}
};
}
public static > Comparator reverseOrder() {
return new Comparator() {
public int compare(T o1, T o2) {
return o2.compareTo(o1);
}
};
}
}
public class MainClass{
public static void main(String[] args) {
Comparator sizeOrder = new Comparator() {
public int compare(String s1, String s2) {
return s1.length() < s2.length() ? -1 : s1.length() > s2.length() ? 1 : s1.compareTo(s2);
}
};
Collection strings = Arrays.asList("AAA", "aaa", "CCC", "f");
System.out.println(Comparators.max(strings));
System.out.println(Comparators.min(strings));
System.out.println(Comparators.max(strings,sizeOrder));
System.out.println(Comparators.min(strings,sizeOrder));
}
}
f
AAA
aaa
f