使用 Apache Beam 查找 2 个列表的笛卡尔积

问题描述

我有 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 Streammapreduce 方法如下:

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

另见:How can I make Cartesian product with Java 8 streams?

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...