一,场景:我们随机的产生两点,测试有多少个会落在单位圆内,多少落在外面。
二,函数解释:
1,parallelize()函数是指内部导入数据。
2,filter()函数功能是对元素进行过滤,对每个元素 应用f函数,返回值为true的元素在RDD中保留,返回值为false的元素将被过滤掉。
3,count()函数,返回整个RDD的元素个数。
代码展示:
import java.util.ArrayList;
import java.util.List;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
public class ComputIntensiveTasks2 {
public static void main(String[] args) {
SparkConf conf=new SparkConf();
conf.set("spark.testing.memory", "2147480000");
System.out.println("连接建立好了,准开始了"+conf);
JavaSparkContext sc=new JavaSparkContext("local","ComputIntensinve",conf);
int NUM_SAMPLES=5;
List<Integer> l=new ArrayList<Integer>(NUM_SAMPLES);
for(int i=0; i<NUM_SAMPLES;i++){
l.add(i);
}
long count=sc.parallelize(l).filter(new Function<Integer,Boolean>(){
public Boolean call(Integer arg0) throws Exception {
double x=Math.random();
double y=Math.random();
return x*x+y*y<1;
}}).count();
System.out.println("Pi is roughly "+4.0*count/NUM_SAMPLES);
}
}