Search code examples
javaarraysscalavectormahout

scala - convert mahout vector to array


I'm using mahout math vector (org.apache.mahout.math.Vector) and want to convert it into an array.

Looking on the documentation I didn't find a function to convert with.

What is the simplest way to convert it (using scala)?


Solution

  • You could use JavaConverters (I don't have mahout, so there could be a minor error in the code):

    val javaIterable = mahoutVector.all()
    import scala.collection.JavaConverters.iterableAsScalaIterableConverter
    val scalaIterable = javaIterable.asScala
    val scalaArray = scalaIterable.toArray
    

    scalaArray now contains Vector.Element objects. If you want to have the double values, you have to map the elements (with .get()):

    [same first three lines as above]
    val scalaArray = scalaIterable.map(_.get()).toArray