java代码实现mapreduce中的map、reduce、filter方法

实现代码如下:

public class MyList {
    public static void main(String[] args) {
        List  aa =new ArrayList<>();
        aa.add(1);
        aa.add(2);
        aa.add(3);
        oneselfList list=new oneselfList(aa);
//        调用map方法
        System.out.println("调用map执行完成的结果");
        list.map(new mymaps() {
            @Override
            public int maptest(int a) {
                return  a+1;
            }
        }).forEach(System.out::println);
//        调用reduce方法
        System.out.println("调用reduce执行完成的结果");
   int  sum =list.reduce(new myreduce() {
          @Override
          public int reducetest(int a, int b) {
              return a+b;
          }
      });
   System.out.println(sum);
//   调用filter方法
        System.out.println("调用filter执行完成的结果");
     list.filtertest(new myfilter() {
            @Override
            public boolean filter(int a) {
                return  a>2;
            }
        }).forEach(System.out::println);
    }
}
class oneselfList{
    private  List list;
    public  oneselfList(List alist){
       this.list=alist;
   }
    public void add (int a){
        list.add(a);
    }
//map方法
    public List map(mymaps mapop){
        List newlist=new ArrayList<>();
        for(Integer i : list){
            newlist.add(mapop.maptest(i));
        }
        return newlist;
    }
//    reduce方法
    public int reduce(myreduce reduce){
        if(list.size()<2){

            try {
                throw  new Exception("长度不够,无法进行聚合");

            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            int a=list.get(0);
            int b=list.get(1);
            int result=reduce.reducetest(a,b);
            for(int i=2;i  filtertest(myfilter filter){
        List newlist=new ArrayList<>();
          for(Integer i:list){
              if(filter.filter(i)){
                 newlist.add(i);
              }
          }
          return newlist;
    }

}
interface  mymaps{
     int maptest(int i);
}
interface myreduce{
    int reducetest(int a,int b);
}
interface myfilter{
   boolean filter(int a);
}

 

你可能感兴趣的:(MapReduce)