java8-06-自定义Collector-Join

[TOC]

声明

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


上一篇文章分享了 Collector 的执行流程。现在就来自定义一个最简单的 JoinCollector 看看。

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

简单实现

static class JoinClollector implements Collector {

    private String seperator = ",";

    @Override
    public Supplier supplier() {
        return () -> new StringBuilder();
    }

    @Override
    public BiConsumer accumulator() {
        return (sb, str) -> {
            if (StringUtils.isNotBlank(str)) {
                sb.append(str).append(seperator);
            }
        };
    }

    @Override
    public BinaryOperator combiner() {
        return (l, r) -> l.append(r);
    }

    @Override
    public Function finisher() {
        return c -> {
            String ret = c.toString();
            if (ret.endsWith(seperator)) {
                return ret.substring(0, ret.length() - 1);
            }
            return ret;
        };
    }

    @Override
    public Set characteristics() {
        return new HashSet<>();
    }
}

简化代码

static class JoinClollector2 implements Collector {

    private String seperator = ",";

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

    @Override
    public BiConsumer accumulator() {
        return (sb, str) -> {
            if (StringUtils.isNotBlank(str)) {
                sb.append(str).append(seperator);
            }
        };
    }

    @Override
    public BinaryOperator combiner() {
        return StringBuilder::append;
    }

    @Override
    public Function finisher() {
        return c -> {
            String ret = c.toString();
            if (ret.endsWith(seperator)) {
                return ret.substring(0, ret.length() - 1);
            }
            return ret;
        };
    }

    @Override
    public Set characteristics() {
        return Collections.emptySet();
    }
}

使用自定义Collector

@Test
public void test() {
    String str = Lists.newArrayList("a", "B", "c", "d")
            .stream().collect(new JoinClollector());
    System.out.println(str);
}

博客源码

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

你可能感兴趣的:(java8-06-自定义Collector-Join)