我有关于客户和他们最喜欢的十大电视节目的数据.到目前为止,我能够获得这些数据JavaRDD<Tuple2<String, Shows[]>>.我能够打印它并检查它是否符合预期,它是.
现在,我需要以下列格式将此数据打印到文件中:
Customer_1 Fav_TV_Show_1
Customer_1 Fav_TV_Show_2
Customer_1 Fav_TV_Show_3
Customer_1 Fav_TV_Show_4
Customer_2 Fav_TV_Show_1
Customer_2 Fav_TV_Show_2
Customer_2 Fav_TV_Show_3
Customer_2 Fav_TV_Show_4
Customer_3 Fav_TV_Show_1
Customer_3 Fav_TV_Show_2
Customer_3 Fav_TV_Show_3
Customer_3 Fav_TV_Show_4
Run Code Online (Sandbox Code Playgroud)
我不知道该怎么做.到目前为止,我试过这个:
// Need a flat pair back
JavaPairRDD<String, Shows> resultPairs = result.mapToPair(
new PairFunction<Tuple2<String,Shows[]>, String, Shows>() {
public Tuple2<String, Shows> call(Tuple2<String, Shows[]> t) {
// But this won't work as I have to return multiple <Customer - Show> pairs
}
});
}
Run Code Online (Sandbox Code Playgroud)
任何帮助深表感谢.
嗯,在键值对的情况下,使用a JavaRDD<Tuple2<String, Shows[]>>而不是JavaPairRDD<String, Shows[]>更舒适的方式有点奇怪.尽管如此,您可以执行以下操作以平坦化结果:
// convert your RDD into a PairRDD format
JavaPairRDD<String, Shows[]> pairs = result.mapToPair(new PairFunction<Tuple2<String,Shows[]>, String, Shows[]>() {
public Tuple2<String, Shows[]> call(Tuple2<String, Shows[]> t) throws Exception {
return t;
}
});
// now flatMap the values in order to split them with their respective keys
JavaPairRDD<String, Shows> output = pairs.flatMapValues(
new Function<Shows[], Iterable<Shows>>() {
public Iterable<Shows> call(Shows[] shows) throws Exception {
return Arrays.asList(shows);
}
});
// do something else with them
output.foreach(new VoidFunction<Tuple2<String, Shows>>() {
public void call(Tuple2<String, Shows> t) throws Exception {
System.out.println(t._1() + " " + t._2());
}
});
Run Code Online (Sandbox Code Playgroud)
或者,您也可以output通过flatMapToPair一步使用手动将数组组合Shows成Iterable如下来获取RDD :
JavaPairRDD<String, Shows> output = result.flatMapToPair(
new PairFlatMapFunction<Tuple2<String, Shows[]>, String, Shows>() {
public Iterable<Tuple2<String, Shows>> call(Tuple2<String, Shows[]> t) throws Exception {
ArrayList<Tuple2<String, Shows>> ret = new ArrayList<>();
for (Shows s : t._2())
ret.add(new Tuple2<>(t._1(), s));
return ret;
}
});
Run Code Online (Sandbox Code Playgroud)
希望它有所帮助.干杯!
| 归档时间: |
|
| 查看次数: |
2862 次 |
| 最近记录: |