java8-07-自定义Collector-ToList

  • 声明
  • 简单实现
  • 简化代码
  • 使用自定义Collector
  • 博客源码

声明

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


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

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

简单实现

static class ToListCollector implements Collector, List> {

    @Override
    public Supplier> supplier() {
        return () -> Lists.newArrayList();
    }

    @Override
    public BiConsumer, T> accumulator() {
        return (list, e) -> list.add(e);
    }

    @Override
    public BinaryOperator> combiner() {
        return (acc1, acc2) -> {
            acc1.addAll(acc2);
            return acc1;
        };
    }

    @Override
    public Function, List> finisher() {
        return (acc) -> acc;
    }

    @Override
    public Set characteristics() {
        Set ret = new HashSet<>();
        ret.add(Characteristics.CONCURRENT);
        ret.add(Characteristics.IDENTITY_FINISH);
        return Collections.unmodifiableSet(ret);
    }
}

简化代码

static class ToListCollector2 implements Collector, List> {

    @Override
    public Supplier> supplier() {
        return ArrayList::new;
    }

    @Override
    public BiConsumer, T> accumulator() {
        return List::add;
    }

    @Override
    public BinaryOperator> combiner() {
        return (acc1, acc2) -> {
            acc1.addAll(acc2);
            return acc1;
        };
    }

    @Override
    public Function, List> finisher() {
        return Function.identity();
    }

    @Override
    public Set characteristics() {
        return Collections.unmodifiableSet(
                EnumSet.of(
                        Characteristics.CONCURRENT,
                        Characteristics.IDENTITY_FINISH
                )
        );
    }
}

使用自定义Collector

@Test
public void testListCollector() {
    List list = IntStream.rangeClosed(1, 5).boxed()
      .collect(new ToListCollector<>());
    System.out.println(list);

    List 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

你可能感兴趣的:(JavaSE)