java8-07-自定义Collector-ToList

2017-12-31  本文已影响31人  hylexus

[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

上一篇下一篇

猜你喜欢

热点阅读