2017-07-18 81 views
2

我嘗試轉換下面的代碼段什麼是Scala版本的ArrayList和Tuple?

public org.apache.spark.mllib.linalg.Vector call(Tuple2<IntWritable, VectorWritable> arg0) 
         throws Exception { 

        org.apache.mahout.math.Vector mahoutVector = arg0._2.get(); 
        Iterator<Element> elements = mahoutVector.nonZeroes().iterator(); 
        ArrayList<Tuple2<Integer, Double>> tupleList = new ArrayList<Tuple2<Integer, Double>>(); 
        while (elements.hasNext()) { 
         Element e = elements.next(); 
         if (e.index() >= nCols || e.get() == 0) 
          continue; 
         Tuple2<Integer, Double> tuple = new Tuple2<Integer, Double>(e.index(), e.get()); 
         tupleList.add(tuple); 
        } 
        org.apache.spark.mllib.linalg.Vector sparkVector = Vectors.sparse(nCols, tupleList); 
        return sparkVector; 
       } 

我是相當新的斯卡拉所以我不知道如何正確地轉換。到目前爲止,我得到了

def transformSvec(x: Vector) : org.apache.spark.mllib.linalg.Vector = { 
    val iter=x.nonZeroes.iterator()  
    //iterate the items and add to an arraylist 
    //or an iterable/seq for scala, if var seq: Seq[(Int, scala.Double)] is chosen then 
    org.apache.spark.mllib.linalg.Vectors.sparse(x.size, seq) 
} 

任何人都可以幫忙嗎?提前致謝。

回答

3

元組來自Scala,而不是Java。在斯卡拉你可以使用正確的語法,雖然(IntWritable, VectorWriteable)是類型的特殊語法Tuple2[IntWriteable, VectorWriteable]

您也可以使用此語法實例化您的元組。 Java代碼

Tuple2<Integer, Double> tuple = new Tuple2<Integer, Double>(e.index(), e.get()); 

變爲

val tuple = (e.index(), e.get()) 

您可以使用ArrayList從斯卡拉如果你喜歡,沒有什麼會阻止你,但它一般者優先,因爲他們有更多的功能使用Scala集合的工作做得更好與斯卡拉的其餘部分。 scala.collection.mutable.ArrayBuffer是相當於java.util.ArrayList的斯卡拉。

但是,在Java環境中,在循環中將事物添加到循環中並不常見。通常你會使用不可變的集合和方法,如map,flatmapfilter來轉換和生成新的集合。在你的情況下,你可以使用

val tupleList = x.nonZeroes.iterator() 
    .filter(e => e.index < ncols) 
    .filter(e => e.get != 0) 
    .map(e => (e.index(), e.get)) 
    .toSeq 

要生成你的序列。

+0

它拋出以下錯誤:「值濾波器不是一個成員java.util.Iterator [org.apache.mahout.math.Vector.Element]「 – user3086871

+1

@ user3086871如果你有一個Java迭代器,你需要先將它轉換爲一個Scala迭代器,'import scala.collection.JavaConverters._'通過該導入,您可以在迭代器中調用'.asScala'將其轉換爲Scala迭代器。 – puhlen

1

在亨利馬烏0.13.0你也可以使用MahoutCollections

import org.apache.mahout.math.scalabindings.MahoutCollections._ 

val a = Array(1.0, 2.0, 3.0) 
val v: Vector = new org.apache.mahout.math.DenseVector(a) 

v.toArray 

你可以傳遞一個數組到火花的構造矢量

+0

這將是使用Mahout的首選方法。 –

相關問題