複数のソースオブジェクトから複数の値をコレクションに抽出する状況があります。私はGuavaの変換でこれを達成しようとしましたが、手動で「平坦化」しなければならないコレクションを回収するという問題に遭遇しました。フラットなコレクションに直接結果を戻す良い方法はありますか?Guavaで1から多数への変換
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関数を置き換えます。 –