问题描述
我有 2 个Parent
:
PCollection
PCollection<List<String>> ListA =
pipeline.apply("getListA",ParDo.of(new getListA()))
PCollection<List<String>> ListB =
pipeline.apply("getListB",ParDo.of(new getListB()))
包含:
ListA
["1","2","3"]
包含:
ListB
我如何以包含以下内容的 ["A","B","C"]
结束:
PCollection
我的搜索指向:
How to do a cartesian product of two PCollections in Dataflow?
但这是使用带有 2 个输出的 coGroupby 处理 KV。 coGroupby 可能可用于创建 2 个列表的笛卡尔积,但我没有看到。
解决方法
看起来每个PCollection中都有一个元素,所以你只需要加入这些元素,然后你就可以在DoFn中自己做笛卡尔积
类似的东西
Flatten.pcollections(ListA,List)
.apply(WithKeys.of(null))
.apply(GroupByKey.create())
之后,您将拥有一个包含单个元素的 PCollection,即一个 KV(null,Iterable(ListA,ListB)),您可以使用一些 for 循环生成笛卡尔积。
,您可以使用 Java 8 Stream:map
和 reduce
方法如下:
JmeterWebApp.jmx
List<String> listA = Arrays.asList("1","2","3");
List<String> listB = Arrays.asList("A","B","C");
List<List<String>> cartesianProduct = Stream.of(listA,listB)
// represent each list element as a singleton list
.map(list -> list.stream().map(Collections::singletonList)
// Stream<List<list<String>>>
.collect(Collectors.toList()))
// intermediate output
//[[1],[2],[3]]
//[[A],[B],[C]]
.peek(System.out::println)
// summation of pairs of inner lists
.reduce((list1,list2) -> list1.stream()
// combinations of inner lists
.flatMap(inner1 -> list2.stream()
// merge two inner lists into one
.map(inner2 -> Stream.of(inner1,inner2)
.flatMap(List::stream)
.collect(Collectors.toList())))
// list of combinations
.collect(Collectors.toList()))
// returns List<List<String>>,otherwise an empty list
.orElse(Collections.emptyList());