Use of foreachActive for spark Vector in Java

倾然丶 夕夏残阳落幕 提交于 2020-01-01 19:40:15

问题


How to write simple code in Java which iterate over active elements in sparse vector?

Lets say we have such Vector:

Vector sv = Vectors.sparse(3, new int[] {0, 2}, new double[] {1.0, 3.0});

I was trying with lambda or Function2 (from three different imports but always failed). If you use Function2 please provide necessary import.


回答1:


Adrian, here is how you can use the foreachActive method on the sparse Vector

    AbstractFunction2<Object, Object, BoxedUnit> f = new AbstractFunction2<Object, Object, BoxedUnit>() {
        public BoxedUnit apply(Object t1, Object t2) {
            System.out.println("Index:" + t1 + "      Value:" + t2);
            return BoxedUnit.UNIT;
        }
    };

    Vector sv = Vectors.sparse(3, new int[]{0, 2}, new double[]{1.0, 3.0});
    sv.foreachActive(f);

This will go through the sparse vector and output:

Index:0      Value:1.0
Index:2      Value:3.0

There are 4 imports:

import org.apache.spark.mllib.linalg.Vector;
import org.apache.spark.mllib.linalg.Vectors;
import scala.runtime.AbstractFunction2;
import scala.runtime.BoxedUnit;


来源:https://stackoverflow.com/questions/28953151/use-of-foreachactive-for-spark-vector-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!