Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 814
Janne Avatar asked Jan 19 '23 02:01

Janne


1 Answers

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

like image 196
Stanislav Levental Avatar answered Jan 30 '23 02:01

Stanislav Levental