Use a Java stream to connect the elements of two collections with separators
•
Java
I have two ways to say:
ImmutableSet<String> firstSet = ImmutableSet.of("1","2","3"); ImmutableSet<String> secondSet = ImmutableSet.of("a","b","c");
I want to get a set that contains the elements of the first set connected to each element of the second set, and a separator, that is, the output should be:
ImmutableSet<String> thirdSet = ImmutableSet.of("1.a","1.b","1.c","2.a","2.b","2.c","3.a","3.b","3.c");
(here "." Is my separator)
I initially thought I could stream the first set and apply collectors on the second set of elements Join () to achieve this, but it doesn't solve my needs
Solution
Looks like you're using guava In this case, you can simply use sets Cartesian product 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) );
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码