Google Guava学习之Ordering
2011-06-08 16:44
351 查看
Guava的Ordering和JDK Comparator相比功能更强。
它非常容易扩展,可以轻松构造复杂的comparator,然后用在容器的比较、排序等操作中。
以下是一个代码实例。
它非常容易扩展,可以轻松构造复杂的comparator,然后用在容器的比较、排序等操作中。
以下是一个代码实例。
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}] } }
相关文章推荐
- Google Guava学习(3)-Guava Ordering类
- Google-Guava学习:排序器Ordering
- Google Guava14.0 瓜娃学习笔记
- Google Guava学习(4)-Guava Range类
- Google Guava学习计划第一章Guava Utilities—Preconditions_ComparisonChain_Strings_CharMatcher
- Guava学习笔记:Google Guava 类库简介
- Google Guava学习笔记
- Google Core Libraries for Java 1.6+ Guava学习-第一篇:总览
- Guava学习笔记:Google Guava 类库简介
- Guava学习笔记【1】:Google Guava 类库简介
- Google Guava学习(7)-Guava集合工具 Bimap接口
- [Google Guava]学习--新集合类型Multiset
- Google Guava学习之BiMap
- Guava学习笔记(一):Google Guava 类库简介
- Guava API学习之Ordering犀利的比较器 编辑
- Guava学习笔记:Google Guava 类库简介
- java开发人员,最应该学习和熟练使用的工具类。google guava.(谷歌 瓜娃)
- Guava学习笔记:Google Guava 类库简介
- Google-Guava学习:用Optional<T>表示可能为null的T类型引用
- Google Guava学习(9)-Guava Cache缓存工具(一)