MeirDayan
MeirDayan

Reputation: 650

How to convert apache.spark.ml.linalg.Vector to arrayList in java?

I am trying to convert apache.spark.ml.linalg.Vector to ArrayList in Java.

The source code is like this:

Vector vector = (Vector) row.get(1);
ArrayList<String> vectorList = new ArrayList<String>(vector);

the error is:

Cannot resolve constructor
'ArrayList(org.apache.spark.ml.linalg.Vector)'

How can I do this?

Upvotes: 1

Views: 627

Answers (1)

Madhu Bhat
Madhu Bhat

Reputation: 15253

You cannot convert a Vector to an ArrayList<String> directly. Vector provides a toArray() method (documentation) which returns an array of type double, using which you can convert it into an ArrayList<String> as below:

        Vector vector = (Vector) row.get(1);
        double[] vectorArray = vector.toArray();
        ArrayList<String> vectorList = new ArrayList<>();
        for (double vectorElement: vectorArray) {
            vectorList.add(String.valueOf(vectorElement));
        }

Upvotes: 2

Related Questions