Spark:RDD.map/mapToPair 如何与 Java 一起工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41058998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:39:40  来源:igfitidea点击:

Spark: How RDD.map/mapToPair work with Java

javaapache-sparktuplesrddkeyvaluepair

提问by rugrag

I have some pairs cw (Integer i, String word) with inumber of occurences of wordin a text file.

我有一些对CW(整数I,串词)与数的出现次数的单词在文本文件中。

I would like to simply have for each pair a new pair c1 (Integer i, 1) with 1 fixed number.

我想简单地为每对添加一对带有 1 个固定数字的新对 c1(整数 i,1)。

It seems to be really trivial but I haven't understood how map/mapToPair functions actually work.

这似乎很简单,但我不明白 map/mapToPair 函数实际上是如何工作的。

JavaPairRDD<Integer, Integer> c1 = cw.map(??? -> new Tuple2<Integer, Integer>(??, 1));

I am working using Java-8.

我正在使用 Java-8。

回答by abaghel

If I understand you correctly, you have below JavaPairRDD.

如果我理解正确的话,你有以下 JavaPairRDD。

JavaPairRDD<Integer, String> cw = ...;

Now you want to create below JavaPairRDD where second value is 1.

现在你想在 JavaPairRDD 下面创建第二个值为 1 的值。

JavaPairRDD<Integer, Integer> c1;

In order to get this, first you have to extract JavaRDD from cwJavaPairRDD and for this you will have to call mapfunction like below. We will extract first value from pair.

为了得到这个,首先你必须从cwJavaPairRDD 中提取 JavaRDD ,为此你必须调用map如下函数。我们将从pair中提取第一个值。

JavaRDD<Integer> cw1 = cw.map(tuple -> tuple._1());

Now you will create new JavaPairRDD from JavaRDD using mapToPairfunction like below.

现在您将使用mapToPair如下函数从 JavaRDD 创建新的 JavaPairRDD 。

JavaPairRDD<Integer, Integer> c1 = cw1.mapToPair(i -> new Tuple2<Integer, Integer>(i, 1));

In single line you can write it like

在单行中,您可以像这样写

JavaPairRDD<Integer, Integer> c1 = cw.map(tuple -> tuple._1()).mapToPair(i -> new Tuple2<Integer, Integer>(i, 1));

回答by KayV

This is what you can try:

这是你可以尝试的:

JavaPairRDD<Integer, Integer> tuples = filtered.mapToPair(
                                            f -> new Tuple2<Integer, Integer>(
                                                       Integer.parseInt(f[0]), 
                                                       Integer.parseInt(f[1])
                                       ));

回答by Brad

Simply ... cw.mapValues(v -> 1);

简单地 ... cw.mapValues(v -> 1);

From the api docs for JavaPairRDD.mapValues()...

来自JavaPairRDD.mapValues()的 api 文档...

Pass each value in the key-value pair RDD through a map function without changing the keys; this also retains the original RDD's partitioning.

通过map函数传递键值对RDD中的每个值,不改变键;这也保留了原始 RDD 的分区。