如何编写类型安全的映射器/集合变换器?
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.
}
});
但这不是类型安全的
答案 0 :(得分:6)
检查番石榴的Lists
课程:
public static <F,T> List<T> transform(List<F> fromList,
Function<? super F,? extends T> function)