私は顧客と彼らのお気に入りのトップ10テレビ番組に関するデータを持っています。これまでのところ、私はこのデータをで取得することができ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
どうすればいいのかわかりません。これまでのところ、私はこれを試しました:
// 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
}
});
}
どんな助けでも大歓迎です。
ええと、キーと値のペアの場合に操作しやすいのでは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());
}
});
あるいは、あなたも得ることができるoutput
使用して、RDDをflatMapToPair
、一の工程で、手動の配列を組み合わせることShows
にIterable
次のように
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;
}
});
お役に立てば幸いです。乾杯!
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加