2016-12-05 78 views
0

火花執行鍵/值對我有一個數據集,我會從文件中讀取,地圖形成在Java中

1 2 3 4 5:9:3 2 1 2 1 
2 3 5:4:1 2 1 
4 5:3:1 2 

我想每行分裂這些,然後創建一個鍵/值其中colon的左邊部分爲colon的相應右邊部分。例如,在第一行中,13映射爲(1,3)22映射爲(2,2)。同樣,第一行將會有(3,1), (4,2), (5,1)。同樣,它應該生成第二行和第三行。

我試圖用map函數分割每一行,然後我試圖通過映射每個左邊部分項目和相應的右邊部分值來創建元組。到目前爲止

代碼:

JavaRDD<List<String>> transactions = data.map(
       new Function<String, List<String>>() { 
        public List<String> call(String line) { 
         String[] parts = line.split(" "); 
         return Arrays.asList(parts); 
        } 
       } 
     ); 

    JavaPairRDD<String, Integer> ones = transactions.mapToPair(
       new PairFunction<List<String>, String, Integer>() { 
        public Tuple2<String, Integer> call(List<String> w) { 

         return new Tuple2<String, Integer>....; 
        } 
       }); 

我打的返回部分。有什麼方法可以獲得所有的鍵/值對嗎? PS:我是apache spark的新手。

回答

1

可以使用flatmap一個相對更優雅的解決方案:

val res = dataset.flatMap(line => { 
    val f = line.split(":", -1) //taking care of the empty values with -1 
    val keys = f(0).split(" ", -1) 
    val values = f(2).split(" ", -1) 
    keys.zip(values) //List[(String, String)], (key, value) pairs for a line 
}) 

res.collect.map(println) 

(1,3) 
(2,2) 
(3,1) 
(4,2) 
(5,1) 
(2,1) 
(3,2) 
(5,1) 
(4,1) 
(5,2) 
+0

感謝您的幫助! :)現在需要將這個scala代碼轉換成Java。 – ashish