简体   繁体   English

在Java中使用foreachActive作为Spark Vector

[英]Use of foreachActive for spark Vector in Java

How to write simple code in Java which iterate over active elements in sparse vector? 如何用Java编写简单代码以迭代稀疏向量中的活动元素?

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). 我正在尝试使用lambda或Function2(来自三个不同的进口,但始终失败)。 If you use Function2 please provide necessary import. 如果您使用Function2,请提供必要的导入。

Adrian, here is how you can use the foreachActive method on the sparse Vector Adrian,这是如何在稀疏Vector上使用foreachActive方法

    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: 进口有4种:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM