Guava提供的Ordering比Comparator强大很多,使用起来非常灵活。下面是个小例子。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
import java.util.Arrays; import java.util.Collections; import java.util.List; import com.google.common.base.Function; import com.google.common.collect.Ordering; public class TryOrdering { public static class A implements Comparable<A> { int a = 1; int b = 2; public A(int a, int b) { this.a = a; this.b = b; } public int getA() { return this.a; } public int getB() { return this.b; } @Override public String toString() { return String.format("{a=%d,b=%d}", this.a, this.b); } @Override public int compareTo(A o) { if (this.a > o.a) { return 1; } else if (this.a < o.b) { return -1; } else { if (this.b > o.b) { return 1; } else if (this.b < o.b) { return -1; } else { return 0; } } } } enum AFunctions implements Function<A, Integer> { GET_A { @Override public Integer apply(A arg0) { return arg0.getA(); } }, GET_B { @Override public Integer apply(A arg0) { return arg0.getB(); } } } public static void main(String[] args) { Ordering<A> aOrder = Ordering.natural() .nullsFirst() .onResultOf(AFunctions.GET_A) .compound( Ordering .natural() .nullsFirst() .onResultOf(AFunctions.GET_B)) .nullsFirst() .reverse(); List<A> as = Arrays.asList( new A(1,2), null, new A(1,3), new A(2,1), new A(2,3), null); System.out.println(aOrder.isOrdered(as)); // false Collections.sort(as, aOrder); System.out.println(as); // [{a=2,b=3}, {a=2,b=1}, {a=1,b=3}, {a=1,b=2}, null, null] System.out.println(aOrder.isOrdered(as)); // true A minA = Collections.min(as, aOrder); System.out.println(minA); // {a=2,b=3} A maxA = Collections.max(as, aOrder); System.out.println(maxA); // null List<A> subAList = aOrder.leastOf(as, 3); System.out.println(subAList); // [{a=2,b=3}, {a=2,b=1}, {a=1,b=3}] } } |