3

I have two sets say:

ImmutableSet<String> firstSet = ImmutableSet.of("1","2","3");
ImmutableSet<String> secondSet = ImmutableSet.of("a","b","c");

I would like to get a set which consists of elements of the first set concatenated with each of the elements of the second, along with a delimiter i.e the output should be:

ImmutableSet<String> thirdSet = ImmutableSet.of("1.a","1.b","1.c","2.a","2.b","2.c","2.c","3.a","3.b","3.c");

(Here "." is my delimiter)

I had initially thought I would be able to do this by streaming the first set and applying Collectors.joining() on the elements of the second, but that won't solve my need.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
Hav3n
  • 251
  • 5
  • 21

2 Answers2

4

I had initially thought I would be able to do this by streaming the first set and applying Collectors.joining() on the elements of the second, but that won't solve my need.

What you can do is stream the first set, and flat map each element with all the elements of the second set.

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toSet;

...

ImmutableSet<String> thirdSet = 
    firstSet.stream()
            .flatMap(s1 -> secondSet.stream().map(s2 -> s1+"."+s2))
            .collect(collectingAndThen(toSet(), ImmutableSet::copyOf));

If you directly want to collect into an ImmutableSet, you create a custom collector using the ImmutableSet's builder (see also How can I collect a Java 8 stream into a Guava ImmutableCollection?).

Community
  • 1
  • 1
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
3

It seems that you are using guava. In that case you can simply use Sets.cartesianProduct method

Set<List<String>> cartesianProduct = Sets.cartesianProduct(firstSet,secondSet);
for (List<String> pairs : cartesianProduct) {
    System.out.println(pairs.get(0) + "." + pairs.get(1));
}

Output:

1.a
1.b
1.c
2.a
2.b
2.c
3.a
3.b
3.c

If you want to collect it in ImmutableSet<String> you can use

ImmutableSet<String> product = ImmutableSet.copyOf(
        cartesianProduct.stream()
                        .map(pairs -> pairs.get(0) + "." + pairs.get(1))
                        .toArray(String[]::new)
);
Pshemo
  • 122,468
  • 25
  • 185
  • 269