【发布时间】:2012-01-15 17:33:14
【问题描述】:
我有一种情况,我想从多个源对象中提取多个值到一个集合中。我试图通过 Guava 的转换来实现这一点,但遇到了一个问题,即我取回了必须手动“展平”的集合集合。有没有一种很好的方法可以将结果直接返回到平面集合中?
private static final Function<Target, Collection<Integer>> EXTRACT_FUNCTION = new Function<SourceObject, Collection<Integer>>() {
@Override
public Collection<Integer> apply(SourceObject o) {
// extract and return a collection of integers from o
return Lists.newArrayList(..);
}
};
Collection<SourceObject> sourceObjects = ...
Collection<Collection<Integer>>> nestedResults = transform(sourceObjects, EXTRACT_FUNCTION);
// Now I have to manually flatten the results by looping and doing addAll over the nestedResults..
// Can this be avoided?
Collection<Integer> results = flattenNestedResults(nestedResults);
【问题讨论】:
标签: java collections transform guava