问题
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