美文网首页
java8-07-自定义Collector-ToList

java8-07-自定义Collector-ToList

作者: hylexus | 来源:发表于2017-12-31 20:01 被阅读31次

    [TOC]

    声明

    这一系列文章旨在帮助大家理解 Collector 的执行流程,至于实现的是否高效、是否优雅、是否合理等暂且不论。


    现在来实现一个和 java.util.stream.Collectors#toList 一样效果的 ToListCollector

    若对 Collector 的各个流程有疑问请移驾此处:http://blog.csdn.net/hylexus/article/details/78941843

    简单实现

    static class ToListCollector<T> implements Collector<T, List<T>, List<T>> {
    
        @Override
        public Supplier<List<T>> supplier() {
            return () -> Lists.newArrayList();
        }
    
        @Override
        public BiConsumer<List<T>, T> accumulator() {
            return (list, e) -> list.add(e);
        }
    
        @Override
        public BinaryOperator<List<T>> combiner() {
            return (acc1, acc2) -> {
                acc1.addAll(acc2);
                return acc1;
            };
        }
    
        @Override
        public Function<List<T>, List<T>> finisher() {
            return (acc) -> acc;
        }
    
        @Override
        public Set<Characteristics> characteristics() {
            Set<Characteristics> ret = new HashSet<>();
            ret.add(Characteristics.CONCURRENT);
            ret.add(Characteristics.IDENTITY_FINISH);
            return Collections.unmodifiableSet(ret);
        }
    }
    

    简化代码

    static class ToListCollector2<T> implements Collector<T, List<T>, List<T>> {
    
        @Override
        public Supplier<List<T>> supplier() {
            return ArrayList::new;
        }
    
        @Override
        public BiConsumer<List<T>, T> accumulator() {
            return List::add;
        }
    
        @Override
        public BinaryOperator<List<T>> combiner() {
            return (acc1, acc2) -> {
                acc1.addAll(acc2);
                return acc1;
            };
        }
    
        @Override
        public Function<List<T>, List<T>> finisher() {
            return Function.identity();
        }
    
        @Override
        public Set<Characteristics> characteristics() {
            return Collections.unmodifiableSet(
                    EnumSet.of(
                            Characteristics.CONCURRENT,
                            Characteristics.IDENTITY_FINISH
                    )
            );
        }
    }
    

    使用自定义Collector

    @Test
    public void testListCollector() {
        List<Integer> list = IntStream.rangeClosed(1, 5).boxed()
          .collect(new ToListCollector<>());
        System.out.println(list);
    
        List<Integer> list2 = Stream.iterate(1, i -> i + 1).limit(5)
          .collect(new ToListCollector2<>());
        System.out.println(list2);
    }
    

    博客源码

    https://github.com/hylexus/blog-src/blob/master/java-core/src/test/java/cn/hylexus/lambda/CollectorTest.java

    相关文章

      网友评论

          本文标题:java8-07-自定义Collector-ToList

          本文链接:https://www.haomeiwen.com/subject/onvagxtx.html