Ben H
Ben H

Reputation: 3236

Concatenate ImmutableSet using Guava

I am used to C# where we have IEnumerable<T>.SelectMany but find myself dabbling in some Java code using Google's Guava library. Is there an equivalent to SelectMany in Guava?

Example: If I have a stream/map construct like this

collections
            .stream()
            .map(collection -> loadKeys(collection.getTenant(), collection.getGroup()))
            .collect(GuavaCollectors.immutableSet());

where loadKeys returns something like ImmutableSet<String>, this function would return ImmutableSet<ImmutableSet<String>> but I want to just flatten them into one ImmutableSet<String>

What's the best way to do that?

Upvotes: 1

Views: 335

Answers (1)

Michał Krzywański
Michał Krzywański

Reputation: 16920

You can use Stream::flatMap method :

collections
        .stream()
        .flatMap(collection -> loadKeys(collection.getTenant(), collection.getGroup()).stream())
        .collect(ImmutableSet.toImmutableSet());

Notice that you get the stream out of loadKeys method result. The result from this should be ImmutableSet<String> assuming that loadKeys returns a Set.

Upvotes: 3

Related Questions