java8 stream 自定义collector

2019-08-06  本文已影响0人  草祭木初

二话不说 直接上代码

public class Test {
    @org.junit.Test
    public void test1 () {
        Stream<String> names = Stream.of("John", "Paul", "George", "John",
                "Paul", "John");
        Map<String, List<String>> m = names.collect(new GroupingBy<String,String>(x->x));
        System.out.print(m.toString());
        // 输出是: {George=[George], John=[John, John, John], Paul=[Paul, Paul]}
    }
}

// 模拟 Collectors.groupingBy()
class GroupingBy<T, K> implements Collector<T, Map<K, List<T>>, Map<K,
        List<T>>> {

    private Function<T, K> tFunction;
    GroupingBy(Function<T, K> tFunction){
        this.tFunction = tFunction;
    }

    @Override
    public Supplier<Map<K, List<T>>> supplier() {
        // 初始化容器
        return HashMap::new;
    }

    @Override
    public BiConsumer<Map<K, List<T>>, T> accumulator() {
        // 业务操作
        return (p,t)-> {
            K k = this.tFunction.apply(t);
            if (p.containsKey(k)) {
                p.get(k).add(t);
            } else {
                p.put(k, new ArrayList<T>(){{add(t);}});
            }
        };
    }

    @Override
    public BinaryOperator<Map<K, List<T>>> combiner() {
        // 并行操作时 合并子项
        return (l, r) -> {
            l.putAll(r);
            return l;
        };
    }

    @Override
    public Function<Map<K, List<T>>, Map<K, List<T>>> finisher() {
        // 这里是最终的返回结果
        return (p)->p;
    }

    @Override
    public Set<Characteristics> characteristics() {
        return Collections.emptySet();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读