我有一種情況,我想從多個源對象中提取多個值到一個集合中。我試圖通過番石榴的轉變來實現這一目標,但遇到了問題,我收回了一些我必須手動「變平」的集合。是否有一種很好的方式直接在平面集合中獲得結果?用番石榴從一個變爲多個
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);
這是正確的。 Iterables.concat將替代您的flattenNestedResults功能。 –