Java 如何打印<;字符串,数组[]>;作为一对平底鞋? 设置:
我有关于客户和他们最喜欢的十大电视节目的数据。到目前为止,我能够在Java 如何打印<;字符串,数组[]>;作为一对平底鞋? 设置:,java,apache-spark,Java,Apache Spark,我有关于客户和他们最喜欢的十大电视节目的数据。到目前为止,我能够在JavaRDD中获得这些数据。我能够打印它,并检查它是否如预期的那样,它是 目标: 现在,我需要以以下格式将这些数据打印到文件中: 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 C
JavaRDD
中获得这些数据。我能够打印它,并检查它是否如预期的那样,它是
目标:
现在,我需要以以下格式将这些数据打印到文件中:
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
问题:
我不知道怎么做。到目前为止,我已经尝试过:
// 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
}
});
}
//需要一对平背
javapairdd resultPairs=result.mapToPair(
新PairFunction(){
公共Tuple2调用(tuple2t){
//但这不起作用,因为我必须返回多对
}
});
}
非常感谢您的帮助。好吧,您得到的是
JavaRDD
而不是javapairdd
,这在键值对的情况下更容易使用,这有点奇怪。尽管如此,为了使结果平坦化,您可以执行以下操作:
// 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());
}
});
希望有帮助。干杯 谢谢!我就快到了(你建议的第二个选择)。只是对如何返回列表感到困惑+1并接受。添加了一个后续问题。使用
saveToTextFile
时,应在文件中以(键、值)
的格式获取对。你能告诉我你到底在做什么吗?也许您应该发布另一个问题。要将JavaRDD转换为JavaPairdd,您可以使用JavaPairdd.fromJavaRDD(JavaRDD):
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;
}
});