Java8新特性JDK8之collector收集器

Java新特性玩转JDK8之collector收集器


流的collect()方法

  • 一个终端操作, 用于对流中的数据进行归集操作,collect方法接受的参数是一个Collector
  • 两个重载方法
    • 方法一 ,通常用来自定义返回值类型,但在实际开发中很少使用
<R> R collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R>combiner);
  • 方法二,传入Collector收集器来对流中结果进行收集,实际开发中常用此方法
<R, A> R collect(Collector<? super T, A, R> collector);

参数Collector 收集器

  • **通常我们不会来自定义Collector收集器。**对于常用的Collector收集器,jdk 8 已经帮我们封装在 Collectors 类中。

👇
👇

Collectors 常用收集器

  • 三大常用收集器
    • Collectors.toList(); // 该收集器将流转换为List集合
    • Collectors.toMap(); // 该收集器将流转换为map集合
    • Collectors.toSet(); // 该收集器将流转换为Set集合
  • 自定义Collection 的结构 数据收集
    • Collectors.toCollection(LinkedList::new)
    • Collectors.toCollection(CopyOnWriteArrayList::new)
    • Collectors.toCollection(TreeSet::new)
  • joining 收集器 👉 章节 7-2
  • partitioningBy 收集器 👉 章节 7-3
  • group by 收集器 👉 章节 7-4 & 7-5
  • summarizing 收集器 👉 章节 7-6

课程代码

public class Main {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("sdfsdf","xxxx","bbb","bbb");
//        List<String> results = list.stream().collect(Collectors.toList());
        // 打印 [bbb, xxxx, sdfsdf] set会去重复所以剩下三个
        System.out.println(list.stream().collect(Collectors.toSet()));
//        List<String> result = list.stream().collect(Collectors.toCollection(LinkedList::new));
        List<String> result = list.stream().collect(Collectors.toCollection(CopyOnWriteArrayList::new));
        Set<String> stringSet = list.stream().collect(Collectors.toCollection(TreeSet::new));
        // 打印 [sdfsdf, xxxx, bbb, bbb]
        System.out.println(result);
        // 打印 [bbb, sdfsdf, xxxx]
        System.out.println(stringSet);
    }
}

原文地址:https://www.yuque.com/haomingzi-kowv5/pmcs3t/ml7tlr

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值