Java8(3)Stream类的collect方法详解

参考书籍:《Java 8函数式编程》

上篇Java8之Stream类限于篇幅,所以把Stream的collect方法单独拿出来写一篇文章。
Stream API中有两种collect方法:

  1. <R, A> R collect(Collector<? super T, A, R> collector);
  2. <R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner);

一般第一种方法用的比较多,第二种方法看起来跟reduce的第三种方法有点类似,也可以用来实现filter、map等操作,但是两者实现方式有区别。我们以实现filter为例:

  • reduce实现filter功能方式:
public static <T> List<T> filter(Stream<T> stream, Predicate<T> predicate) {
    return stream.reduce(new ArrayList<T>(), (acc, t) -> {
        if (predicate.test(t)) {
            List<T> lists = new ArrayList<T>(acc);
            lists.add(t);
            return lists;
        }
        return acc;
    }, (List<T> left, List<T> right) -> {
        List<T> lists = new ArrayList<T>(left);
        lists.addAll(right);
        return lists;
    });
}
  • collect实现filter功能方式:
public static <T> List<T> filter(Stream<T> stream, Predicate<T> predicate) {
    return stream.collect(ArrayList::new, (acc, t) -> {
        if (predicate.test(t))
            acc.add(t);
    }, ArrayList::addAll);
}

很明显collect实现方式更简洁,效率更高。那么reduce为什么每次都new一次ArrayList,而不是直接acc.add(t)再返回acc呢?因为reduce规定第二个参数BiFunction<U, ? super T, U> accumulator表达式不能改变其自身参数acc原有值,所以每次都要new ArrayList<T>(acc),再返回新的list。

下面来看看第一种collect方法,它离不开Collectors工具类。其实上篇的代码已经涉及到了该方法,比如collect(Collectors.toList())转换成list集合。其他API如下:

  1. Collectors.toSet():转换成set集合。

  2. Collectors.toCollection(TreeSet::new):转换成特定的set集合。
    TreeSet<Integer> collect2 = Stream.of(1, 3, 4).collect(Collectors.toCollection(TreeSet::new));

  3. Collectors.toMap(x -> x, x -> x + 1):转换成map。
    Map<Integer, Integer> collect1 = Stream.of(1, 3, 4).collect(Collectors.toMap(x -> x, x -> x + 1));

  4. Collectors.minBy(Integer::compare):求最小值,相对应的当然也有maxBy方法。

  5. Collectors.averagingInt(x->x):求平均值,同时也有averagingDouble、averagingLong方法。
    Stream.of(1, 2, 3).collect(Collectors.averagingInt(x->x));

  6. Collectors.summingInt(x -> x)):求和。

  7. Collectors.summarizingDouble(x -> x):可以获取最大值、最小值、平均值、总和值、总数。
    DoubleSummaryStatistics s = Stream.of(1, 3, 4).collect(Collectors.summarizingDouble(x -> x));
    s.getAverage();//平均值

  8. Collectors.groupingBy(x -> x):有三种方法,查看源码可以知道前两个方法最终调用第三个方法,第二个参数默认HashMap::new 第三个参数默认Collectors.toList(),参考SQL的groupBy。
    Map<Integer, List<Integer>> map = Stream.of(1, 3, 3, 4).collect(Collectors.groupingBy(x -> x));
    Map<Integer, Long> map = Stream.of(1, 3, 3, 4).collect(Collectors.groupingBy(x -> x, Collectors.counting()));
    HashMap<Integer, Long> hashMap = Stream.of(1, 3, 3, 4).collect(Collectors.groupingBy(x -> x, HashMap::new, Collectors.counting()));

  9. Collectors.partitioningBy(x -> x > 2),把数据分成两部分,key为ture/false。第一个方法也是调用第二个方法,第二个参数默认为Collectors.toList()
    Map<Boolean, List<Integer>> collect5 = Stream.of(1, 3, 4).collect(Collectors.partitioningBy(x -> x > 2));
    Map<Boolean, Long> collect4 = Stream.of(1, 3, 4).collect(Collectors.partitioningBy(x -> x > 2, Collectors.counting()));

  10. Collectors.joining(","):拼接字符串。
    Stream.of("a", "b", "c").collect(Collectors.joining(","));

  11. Collectors.reducing(0, x -> x + 1, (x, y) -> x + y)):在求累计值的时候,还可以对参数值进行改变,这里是都+1后再求和。跟reduce方法有点类似,但reduce方法没有第二个参数。
    Stream.of(1, 3, 4).collect(Collectors.reducing(0, x -> x + 1, (x, y) -> x + y));

  12. Collectors.collectingAndThen(Collectors.joining(","), x -> x + "d"):先执行collect操作后再执行第二个参数的表达式。这里是先拼接字符串,再在最后拼接 "d"。
    Stream.of("a", "b", "c").collect(Collectors.collectingAndThen(Collectors.joining(","), x -> x + "d"));

  13. Collectors.mapping(...):跟map操作类似,只是参数有点区别。
    Stream.of("a", "b", "c").collect(Collectors.mapping(x -> x.toUpperCase(), Collectors.joining(",")));


下篇Lambda表达式的真实面目

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

推荐阅读更多精彩内容

  • Int Double Long 设置特定的stream类型, 提高性能,增加特定的函数 无存储。stream不是一...
    patrick002阅读 1,282评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,896评论 18 139
  • Java8 in action 没有共享的可变数据,将方法和函数即代码传递给其他方法的能力就是我们平常所说的函数式...
    铁牛很铁阅读 1,274评论 1 2
  • Jav8中,在核心类库中引入了新的概念,流(Stream)。流使得程序媛们得以站在更高的抽象层次上对集合进行操作。...
    仁昌居士阅读 3,688评论 0 6
  • 二零一六年新年规划✨ 1.有计划的广泛阅读 2.坚持日记 3.坚持运动 马甲线训练 4.坚持舞蹈基本功练习 自学吉...
    闪亮亮的女神柯阅读 216评论 3 0