java8-06-自定義Collector-JoinCollector

[TOC]java

聲明

這一系列文章旨在幫助你們理解 Collector 的執行流程,至於實現的是否高效、是否優雅、是否合理等暫且不論。git


上一篇文章分享了 Collector 的執行流程。如今就來自定義一個最簡單的 JoinCollector 看看。github

若對 Collector 的各個流程有疑問請移駕此處:http://blog.csdn.net/hylexus/...app

簡單實現

static class JoinClollector implements Collector<String, StringBuilder, String> {

    private String seperator = ",";

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

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

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

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

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

簡化代碼

static class JoinClollector2 implements Collector<String, StringBuilder, String> {

    private String seperator = ",";

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

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

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

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

    @Override
    public Set<Characteristics> 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/bl...ide

相關文章
相關標籤/搜索