使用 java 流连接带有分隔符的两个集合的元素

Concatenate elements of two sets with delimiter using java stream

我有两套说:

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

我想要一个集合,其中包含第一个集合的元素与第二个集合的每个元素连接在一起,以及一个分隔符,即输出应该是:

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

(这里的“.”是我的分隔符)

我最初认为我可以通过流式传输第一组并在第二组的元素上应用 Collectors.joining() 来做到这一点,但这不能解决我的需要。

看来你用的是番石榴。在这种情况下,您可以简单地使用 Sets.cartesianProduct 方法

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

输出:

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

如果您想在 ImmutableSet<String> 中收集它,您可以使用

ImmutableSet<String> product = ImmutableSet.copyOf(
        cartesianProduct.stream()
                        .map(pairs -> pairs.get(0) + "." + pairs.get(1))
                        .toArray(String[]::new)
);

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.

您可以做的是流式传输第一组,然后将每个元素与第二组的所有元素平面映射。

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

如果您想直接收集到 ImmutableSet,您可以使用 ImmutableSet 的构建器创建自定义收集器(另请参阅 )。