java8 自定义收集器Collector

Collectors类的一些静态方法
这里写图片描述

import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Collector.Characteristics;
import java.util.stream.Collectors;

import org.junit.Test;

import com.cbzk.lambda.Employee;
import com.cbzk.lambda.Employee.Status;

/*
 * 自定义收集器
 * 需要重写collector接口
 * public interface Collector<T, A, R> {
        Supplier<A> supplier();
        BiConsumer<A, T> accumulator();
        Function<A, R> finisher();  //最后要做的转换操作
        BinaryOperator<A> combiner();
        Set<Characteristics> characteristics();
}
T要收集项目的泛型
A累加器的类型
R收集操作得到的对象(不一定是集合)


Characteristics是一个包含三个项目的枚举。
UNORDERED——归约结果不受流中项目的遍历和累积顺序的影响。
CONCURRENT——accumulator函数可以从多个线程同时调用,且该收集器可以并行归
约流。如果收集器没有标为UNORDERED, 那它仅在用于无序数据源时才可以并行归约。
IDENTITY_FINISH——这表明完成器方法返回的函数是一个恒等函数,可以跳过。

这种情况下,累加器对象将会直接用作归约过程的最终结果。这也意味着,将累加器A不加检
查地转换为结果R是安全的。
我们迄今开发的ToListCollector是IDENTITY_FINISH的,因为用来累积流中元素
List已经是我们要的最终结果,用不着进一步转换了,但它并不是UNORDERED,因为用在有序
流上的时候,我们还是希望顺序能够保留在得到的List中。最后,它是CONCURRENT的,但我们
刚才说过了,仅仅在背后的数据源无序时才会并行处理


//通过collect代码认识一下:
                if (isParallel()
                && (collector.characteristics().contains(Collector.Characteristics.CONCURRENT))
                && (!isOrdered() || collector.characteristics().contains(Collector.Characteristics.UNORDERED))) {
                //并发
                }
即并发条件:
在Collector.Characteristics.CONCURRENT的基础上,收集器Collector具有Characteristics.UNORDERED特性或者原始数据是无序的时才应用并发;

 String concat = stringStream.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();

发现了一个小现象
在使用java8的lambda时,
有的编译报错并不是因为你写的有问题,而是你没有写返回值造成的;
比如: HashMap<String, Integer> map3 = emps.stream()
                                         .collect(HashMap::new, (m, emp) -> m.put(emp.getName(), emp.getAge()),HashMap::putAll);
直接写 emps.stream()
         .collect(HashMap::new, (m, emp) -> m.put(emp.getName(), emp.getAge()),HashMap::putAll);
        就会报错,编译器不认识m到底是什么,估计跟前面的 HashMap<String, Integer>推断有关;

参考:                  
http://blog.jobbole.com/104067/
 */
public class StreamDemo6 {


    List<Employee> emps = Arrays.asList(
            new Employee(102, "李四aa", 59, 6666.66, Status.BUSY),
            new Employee(102, "李四aaa", 60, 6666.66, Status.BUSY),
            new Employee(101, "张三bb", 18, 9999.99, Status.FREE),
            new Employee(103, "王五cc", 28, 3333.33, Status.VOCATION),
            new Employee(104, "赵六dd", 8, 7777.77, Status.BUSY),
            new Employee(104, "赵六dd", 9, 7777.77, Status.FREE),
            new Employee(104, null, 25, 7777.77, Status.FREE),
            new Employee(105, "丽丽", null, 5555.55, Status.BUSY)
    );


    //实现toList的功能
    //顺序流
    @Test
    public void test() {
        List<Employee> res = emps.stream()
            .limit(2)
            .collect(Collectors.toList());
        //方式1 自定义收集器
        List<Employee> res2 = emps.stream()
            .limit(2)
            .collect(new MyToList<Employee>());
        System.out.println(res2);

        //方式2 重写collect方法的三个参数
        //这种直接写的不灵活,而且不容易看懂,且不能设置属性,其属性默认为IDENTITY_FINISH,CONCURRENT
//      collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner);
        //注意:第三个合并参数,Collector里面是BinaryOperator,而collect里面是BiConsumer
        //所以可以直接
        List<Employee> res3 = emps.stream()
            .limit(2)
//          .collect(ArrayList::new, List::add,(list1,list2)->list1.addAll(list2));
            .collect(ArrayList::new,List::add,List::addAll);
        System.out.println(res3);

        //方式3:使用Collector.of 这个可以理解成自定义收集器的 完整封装版  
        List<Employee> res4=emps.stream()
                                .limit(2)
                                .collect(Collector.of(ArrayList::new, List::add
                                , (list1,list2)->{list1.addAll(list2);
                                                        return list1;}

                     , new Characteristics[]   {Characteristics.IDENTITY_FINISH,Characteristics.CONCURRENT}));
        System.out.println(res4);
    }

    //并行流
//  list集合本身是有序的,所以并行不起来
    @Test
    public void test1() {
        List<Employee> res = emps.stream()
                                 .limit(2)
                                 .parallel()
                                 .collect(Collectors.toList());
        System.out.println(res);

        List<Employee> res2 = emps.stream()
                                  .parallel()
                                  .collect(new MyToList<Employee>());
            System.out.println(res2);

        List<Employee> res3 = emps.stream()
                                  .parallel()
                                  .collect(ArrayList::new,List::add,List::addAll);
            System.out.println(res3);

    }


    //实现tomap的功能
    //顺序流
    @Test
    public void test2() {
        //一般转换map  
        //它存在2个问题,1.对于重复key报错  2.对于vlauenull报错
//      Map<String, Integer> map1 = emps.stream()
//          .collect(Collectors.toMap(Employee::getName, Employee::getAge));
//      System.out.println(map1);

        //解决方式1:使用collect的三个入参 自定义收集器
        Map<String,Integer> map2= emps.stream()
            .collect(HashMap::new,( map, emp) ->                                                                                                                                                                           
                                map.put(emp.getName(),emp.getAge()),Map::putAll);
        System.out.println(map2);

        //解决方式2:自已自定义收集器
        Map<String, Integer> map3 = emps.stream()
                                        .collect(MyToMap.toMap(Employee::getName, Employee::getAge));
        System.out.println(map3);

        //因为toMap方法里面使用merge方法,不允许valuenull的,所以要使其避免那2个问题,必须绕开merge方法
        //解决方式3  使用 Collector.of方法  其实就是方式2的简写版
        //当使用顺序流使用时,(hmap1,hmap2)->{hmap1.putAll(hmap2);return hmap1; 没有作用,可以直接抛异常处理
        //当使用并行流时,(hmap1,hmap2)->{hmap1.putAll(hmap2);return hmap1;就需要这句,但并不一定是并行
        Map<String,Integer> map4=emps.stream()
            .collect(Collector.of(HashMap::new, ( map, emp) -> map.put(emp.getName(),emp.getAge())
                                                               , (hmap1,hmap2)->{ throw new UnsupportedOperationException();}
                                                               , new Characteristics[]{Characteristics.IDENTITY_FINISH}));
        System.out.println(map4);
        //小结:上面的解决方式本质都是:自定义构造器
    }


    //并行流
    //合并函数需要这句:(hmap1,hmap2)->{hmap1.putAll(hmap2);return hmap1;
    @Test
    public void test2_1()  {
        //方式1
        Map<String,Integer> map1= emps.stream()
                                      .parallel()
                                      .collect(HashMap::new,( map, emp) -> map.put(emp.getName(),emp.getAge()),Map::putAll);
            System.out.println(map1);

        //方式2
        Map<String, Integer> map2 = emps.stream()
                .parallel()
                .collect(MyToMap.toMap(Employee::getName, Employee::getAge,(hmap1,hmap2)->{hmap1.putAll(hmap2);return hmap1;}));
        System.out.println(map2);

        //方式3
        Map<String,Integer> map3=emps.stream()
                                     .parallel()
                                     .collect(Collector.of(HashMap::new, ( map, emp) -> map.put(emp.getName(),emp.getAge())
                                                                   , (hmap1,hmap2)->{hmap1.putAll(hmap2);return hmap1;}
                                                                   , new Characteristics[]{Characteristics.IDENTITY_FINISH}));
        System.out.println(map3);           
    }

}



//如果MyToList不带泛型,那么后面的参数就是具体的类了
class MyToList<T> implements Collector<T, List<T>, List<T>>{
    //初始化
    @Override
    public Supplier<List<T>> supplier() {
//      return ()->new ArrayList<>();
        return ArrayList::new;
    }

    //累计遍历,累加器
    @Override
    public BiConsumer<List<T>, T> accumulator() {
        return List::add;
    }

    //合并结果   
    @Override
    public BinaryOperator<List<T>> combiner() {
        return (list1,list2)->{
             list1.addAll(list2);
             return list1;
        };
    }

    //对结果进行处理
    //这里直接返回
    @Override
    public Function<List<T>, List<T>> finisher() {
//      return e->e;
        return Function.identity();
    }

    //设置属性
    @Override
    public Set<Characteristics> characteristics() {
        return Collections.unmodifiableSet(EnumSet.of(Characteristics.CONCURRENT,Characteristics.IDENTITY_FINISH));
    }

}


//

class EasyToMapCollector<T,K, V> implements Collector<T, Map<K, V>, Map<K, V>> {

    private Function<? super T, ? extends K> keyMapper;

    private Function<? super T, ? extends V> valueMapper;

    private BinaryOperator<Map<K, V>> binOp;


    //2个参数的,只能是顺序流
    public EasyToMapCollector(Function<? super T, ? extends K> keyMapper,
            Function<? super T, ? extends V> valueMapper) {
//      this.keyMapper = keyMapper;
//      this.valueMapper = valueMapper;
        this(keyMapper,valueMapper,null);
    }

    public EasyToMapCollector(Function<? super T, ? extends K> keyMapper,
                              Function<? super T, ? extends V> valueMapper, BinaryOperator<Map<K, V>> binOp) {
        this.keyMapper = keyMapper;
        this.valueMapper = valueMapper;
        this.binOp=binOp;
    }


    @Override
    public BiConsumer<Map<K, V>, T> accumulator() {
        return (map, element) -> map.put(keyMapper.apply(element), valueMapper.apply(element));
        //如果同一个key对应多个value,想让key匹配那个部位null的value,可以用
//      return (map,element)->map.putIfAbsent(keyMapper.apply(element), valueMapper.apply(element));
    }

    @Override
    public Supplier<Map<K, V>> supplier() {
        return HashMap::new;
    }

    @Override
    public BinaryOperator<Map<K, V>> combiner() {
//      return null;
        //如果不用这个方法最好是抛异常
//      throw new UnsupportedOperationException();
        return binOp;
    }

    @Override
    public Function<Map<K, V>, Map<K, V>> finisher() {
        return Function.identity();
    }

    @Override
    public Set<Characteristics> characteristics() {
        return Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH));
    }

}


 final class  MyToMap {
        public  static  <T,K, V> Collector<T, ?, Map<K, V>> toMap(Function<T, K> f1, Function<T, V> f2) {
            return new EasyToMapCollector<T,K,V>(f1, f2);
        }

        public  static  <T,K, V> Collector<T, ?, Map<K, V>> toMap(Function<T, K> f1, Function<T, V> f2,BinaryOperator<Map<K, V>> binOp) {
            return new EasyToMapCollector<T,K,V>(f1, f2,binOp);
        }

 }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值