您的位置:首页 > 编程语言 > Go语言

Google Guava学习之Ordering

2011-06-08 16:44 351 查看
Guava的Ordering和JDK 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}]
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: