Janne
Janne

Reputation: 3767

Transforming from one to many with Guava

I have situation where I want to extract multiple values from multiple source objects into a collection. I tried to achieve this with Guava's transform, but ran into the problem that I get back a collection of collections which I have to 'flatten' manually. Is there a nice way to get the results back directly in a flat collection?

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);

Upvotes: 4

Views: 2477

Answers (2)

wyz
wyz

Reputation: 761

What you are asking is a reduce / fold method. Currently Guava does not support it though there is an open issue: http://code.google.com/p/guava-libraries/issues/detail?id=218

Maybe it's a better idea that you do not use a Function, but iterate it and add to one collection. Guava is a great framework but it cannot do everything.

Upvotes: 1

Stanislav Levental
Stanislav Levental

Reputation: 2235

You can use Guava's Iterables.concat(Iterable<E>... coll) to group few iterable results

Upvotes: 8

Related Questions