如何编写集合的类型安全映射器/转换器?
class Bean {
public int value;
}
List<Bean> beans = ..
List<Integer> ints = Lib.map(beans, b => b.value);
使用Apache Commons-Collections,它看起来像这样:
Collection<Integer> ints = CollectionUtils.collect(beans, new Transformer() {
@Override
public Object transform(Object input) {
return null; //cast here, dereference etc.
}
});
但是这不是类型安全的
查看番石榴的Lists
类:
public static <F,T> List<T> transform(List<F> fromList,
Function<? super F,? extends T> function)
API docs here