【发布时间】:2014-04-30 21:22:19
【问题描述】:
我经常使用Map<U,V>,我转换和过滤得到另一个Map<U,V'>,但是转换非常冗长,我在问题Guava: how to combine filter and transform?中看到FluentIterable类,是否可以使用它来简化下列的 ?
public class GuavaTest {
public static class A{
int a;
int b;
int c;
public A(int a, int b, int c){
this.a=a; this.b=b; this.c=c;
}
}
public static void main(String[] args) {
//Example 2
final Map<String, A> map =Maps.newHashMap();
map.put("obj1",new A(1,1,1)); map.put("obj2",new A(1,2,1));
map.put("obj3",new A(1,3,1)); map.put("obj4",new A(1,4,1));
Function<A, Integer> function = new Function<A, Integer>() {
@Nullable
@Override
public Integer apply(@Nullable A input) {
return input.b;
}
};
Predicate<Integer> isPair = new Predicate<Integer>() {
@Override
public boolean apply(@Nullable Integer input) {
return input % 2 == 0;
}
};
//Can I use FluentIterable here ??
Map<String, Integer> stringIntegerMap = Maps.transformValues(map, function);
Map<String, Integer> stringIntegerMap1 = Maps.filterValues(stringIntegerMap, isPair);
}
}
【问题讨论】:
标签: java guava generic-programming