Java8中Collectors的使用

2023-11-14

前言: 基本类型的流没有这个用法

averagingDouble,averagingInt,averagingLong

平均值计算,返回的都是Double类型

        List<Dog> users = Arrays.asList(
                new Dog("a",9),
                new Dog("b",10),
                new Dog("c",10),
                new Dog("d",13),
                new Dog("e",14));

        Double collect = users.stream().collect(Collectors.averagingDouble(x -> x.getAge()));
        System.out.println(collect);//11.2
        Double collect1 = users.stream().collect(Collectors.averagingInt(x -> x.getAge()));
        System.out.println(collect1);//11.2
        Double collect2 = users.stream().collect(Collectors.averagingLong(x -> x.getAge()));
        System.out.println(collect2);//11.2

collectingAndThen

List<Dog> users = Arrays.asList(
                new Dog("a",9),
                new Dog("b",10),
                new Dog("c",10),
                new Dog("d",13),
                new Dog("e",14));

        Map<Integer, Long> collect = users.stream().collect(Collectors.groupingBy(x -> x.getAge(), Collectors.counting()));
        System.out.println(collect);//{9=1, 10=2, 13=1, 14=1}
        Integer collect1 = users.stream().collect(Collectors.collectingAndThen(Collectors.groupingBy(x -> x.getAge()), map -> map.size()));
        System.out.println(collect1);//4
  • 第一个参数为要做的操作,第二个参数对第一个参数收集到的结果进行如何的处理

counting

        //创建数组 元素为0~9
        List<Integer> collect = Stream.iterate(0, x -> x + 1).limit(10).collect(Collectors.toList());

        Long collect1 = collect.stream().collect(Collectors.counting());
        System.out.println(collect1);

groupingBy

  1. 一个参数表示按照哪个值来分组,这个值为key,其中的value就为符合k的集合
  2. 两个参数表示:第一个参数同上,第二个参数可以对value集合再次进行流操作
  3. 三个参数表示:第一个参数同上,第二个参数表示要返回什么样的Map,第三个参数可以对value集合再次进行流操作
        List<Dog> users = Arrays.asList(
                new Dog("a",9),
                new Dog("b",10),
                new Dog("c",10),
                new Dog("d",13),
                new Dog("e",14));
        //按照年龄来分类,key为年龄,value为相同年龄的集合
        Map<Integer, List<Dog>> collect = users.stream().collect(Collectors.groupingBy(x -> x.getAge()));
        //{9=[Dog{name='a', age=9}], 10=[Dog{name='b', age=10}, Dog{name='c', age=10}], 13=[Dog{name='d', age=13}], 14=[Dog{name='e', age=14}]}
        System.out.println(collect);
        //{9=[], 10=[Dog{name='c', age=10}], 13=[], 14=[]}
        Map<Integer, Set<Dog>> c = users.stream().collect(Collectors.groupingBy(x -> x.getAge(), Collectors.filtering(x -> x.getName().equals("c"), Collectors.toSet())));
        //
        TreeMap<Object, Set<Dog>> collect1 = users.stream().collect(Collectors.groupingBy(x -> x.getAge(), TreeMap::new, Collectors.toSet()));
        System.out.println(collect1);

groupingByConcurrent

使用同groupingBy,但是返回的是线程安全的集合。

joining

          String[] strings = {"gs","sb","dpz"};
        String collect = Arrays.stream(strings).collect(Collectors.joining());
        String collect1 = Arrays.stream(strings).collect(Collectors.joining(","));
        String collect2 = Arrays.stream(strings).collect(Collectors.joining(",", "[", "]"));
        System.out.println(collect);//gssbdpz
        System.out.println(collect1);//gs,sb,dpz
        System.out.println(collect2);//[gs,sb,dpz]

mapping

        //创建数组 元素为0~9
        List<Integer> collect = Stream.iterate(0, x -> x + 1).limit(10).collect(Collectors.toList());

        //过滤
        Set<Integer> collect1 = collect.stream().collect(Collectors.mapping(x -> x, Collectors.toSet()));
        //等价于
        Set<Integer> collect2 = collect.stream().map(x -> x).collect(Collectors.toSet()); 

maxBy,minBy

  1. maxBy:return (a, b) -> comparator.compare(a, b) >= 0 ? a : b 如果返回的小于0,取b
  2. minBy:return (a, b) -> comparator.compare(a, b) <= 0 ? a : b 如果返回结果小于0,取a
 //创建数组 元素为0~9
        List<Integer> collect = Stream.iterate(0, x -> x + 1).limit(10).collect(Collectors.toList());

        Optional<Integer> collect1 = collect.stream().collect(Collectors.maxBy((x, y) -> -1));
        Optional<Integer> collect2 = collect.stream().collect(Collectors.minBy((x, y) -> -1));
        System.out.println(collect1); //9
        System.out.println(collect2); //0

partitioningBy

1.一个参数: 根据过滤把结果集分为两组存在Map中,键为true的为一组,键为false的为一组,值为List存放元素
2. 两个参数:同上,但是第二个参数表示再次过滤Map中的Value。

 //创建数组 元素为0~9
        List<Integer> collect = Stream.iterate(0, x -> x + 1).limit(10).collect(Collectors.toList());

        Map<Boolean, List<Integer>> collect2 = collect.stream().collect(Collectors.partitioningBy(x -> x > 2));
        System.out.println(collect2); // {false=[0, 1, 2], true=[3, 4, 5, 6, 7, 8, 9]}
        Map<Boolean, Integer> collect1 = collect.stream().collect(Collectors.partitioningBy(x -> x > 2, Collectors.reducing(0,(x, y) -> Math.min(x, y))));
        System.out.println(collect1); // {false=0, true=0}

reducing

 //创建数组 元素为0~9
        List<Integer> collect = Stream.iterate(0, x -> x + 1).limit(10).collect(Collectors.toList());

        //因为提供了第一个参数,确定了类型,返回值为该类型对象,第二个参数x,y为流中的两个值进行操作
        Integer collect1 = collect.stream().collect(Collectors.reducing(0, (x, y) -> Math.min(x, y)));
        //返回值Optional<T>,第二个参数x,y为流中的两个值进行操作
        Optional<Integer> collect2 = collect.stream().collect(Collectors.reducing((x, y) -> Math.min(x, y)));
        //因为提供了第一个参数,确定了类型,返回值为该类型对象,第二个参数还可以对每个元素进行一次操作,第三个参数x,y为流中的两个值进行操作
        Integer collect3 = collect.stream().collect(Collectors.reducing(0, x -> x+1, (x, y) -> Math.max(x, y)));

summarizingDouble,summarizingInt,summarizingLong

方法 描述
summarizingDouble(ToDoubleFunction<? super T> mapper) 接口实现方法为传入一个当前元素,返回值为对应的基本类型,收集后得到一个xxxSummaryStatistics实例,属性包括最大,最小等属性
summarizingInt(ToIntFunction<? super T> mapper) 同上
summarizingLong(ToLongFunction<? super T> mapper) 同上
        //创建数组 元素为0~9
        List<Integer> collect = Stream.iterate(0, x -> x + 1).limit(10).collect(Collectors.toList());
        //Collectors.summarizingInt(ToIntFunction<? super T> mapper)
        IntSummaryStatistics collect1 = collect.stream().collect(Collectors.summarizingInt(x -> x));
        System.out.println(collect1);//IntSummaryStatistics{count=10, sum=45, min=0, average=4.500000, max=9}
        DoubleSummaryStatistics collect2 = collect.stream().collect(Collectors.summarizingDouble(x -> x));
        System.out.println(collect2);//DoubleSummaryStatistics{count=10, sum=45.000000, min=0.000000, average=4.500000, max=9.000000}
        LongSummaryStatistics collect3 = collect.stream().collect(Collectors.summarizingLong(x -> x));
        System.out.println(collect3);//LongSummaryStatistics{count=10, sum=45, min=0, average=4.500000, max=9}

summingDouble,summingInt,summingLong

方法 描述
summingDouble(ToDoubleFunction<? super T> mapper) 接口实现方法为传入一个当前元素,返回值为对应的基本类型,收集后得到一个对应的包装类,值就为和
summingInt(ToIntFunction<? super T> mapper) 同上
summingLong(ToLongFunction<? super T> mapper) 同上
        //创建数组 元素为0~9
        List<Integer> collect = Stream.iterate(0, x -> x + 1).limit(10).collect(Collectors.toList());
        //Collectors.summarizingInt(ToIntFunction<? super T> mapper)
        Double collect1 = collect.stream().collect(Collectors.summingDouble(x -> x));
        Integer collect2 = collect.stream().collect(Collectors.summingInt(x -> x));
        Long collect3 = collect.stream().collect(Collectors.summingLong(x -> x));

toCollection

        Integer[] a = {1,2,3,4,5,6,7,8,9,10};
        //Collectors.toCollection 返回指定集合类型,要求:必须为collectors的子类
        Arrays.stream(a).collect(Collectors.toCollection(TreeSet::new));
        Arrays.stream(a).collect(Collectors.toCollection(()->new TreeSet<>()));

toConcurrentMap

 Integer[] a = {1,2,3,4,5,6,7,8,9,10};
        //toConcurrentMap.toMap 使用
        //1.两个参数,一个key,一个value 组成任意Map(key,value的类型由返回值类型决定)
        //{1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9, 10=10}
        ConcurrentMap<String, String> collect = Arrays.stream(a).collect(Collectors.toConcurrentMap(x -> x.toString(), x -> x.toString()));
        //2.三个参数,第三个参数决定key冲突时怎么处理,(x,y) 代表两个冲突k的value值
        //{1=11} key全为1,value每次都保存最新的那个
        ConcurrentMap<String, String> collect1 = Arrays.stream(a).collect(Collectors.toConcurrentMap((x) -> "1", x -> String.valueOf(x+1),(x, y)->y));
        3.四个参数,第四个代表要返回的Map类型,默认ConcurrentMap,只允许ConcurrentMap的子类
        ConcurrentSkipListMap<String, String> collect2 = Arrays.stream(a).collect(Collectors.toConcurrentMap((x) -> "1", x -> String.valueOf(x + 1), (x, y) -> y, ConcurrentSkipListMap::new));

toList,toSet

 Integer[] a = {1,2,3,4,5,6,7,8,9,10,1};

        //去重,组成set [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        Set<Integer> set = Arrays.stream(a).collect(Collectors.toSet());
        //直接组成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1]
        List<Integer> list = Arrays.stream(a).collect(Collectors.toList());

toMap

使用例子:

        Integer[] a = {1,2,3,4,5,6,7,8,9,10};
        //Collectors.toMap 使用
        //1.两个参数,一个key,一个value 组成任意Map(key,value的类型由返回值类型决定)
        //{1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9, 10=10}
        Map<String, String> collect = Arrays.stream(a).collect(Collectors.toMap(x -> x.toString(), x -> x.toString()));
        //2.三个参数,第三个参数决定key冲突时怎么处理,(x,y) 代表两个冲突k的value值
        //{1=11} key全为1,value每次都保存最新的那个
        Map<String, String> collect1 = Arrays.stream(a).collect(Collectors.toMap((x) -> "1", x -> String.valueOf(x+1),(x,y)->y));
        //3.四个参数,第四个代表要返回的Map类型,默认hashMap
        Map<String, String> collect2 = Arrays.stream(a).collect(Collectors.toMap((x) -> "1", x -> String.valueOf(x+1),(x,y)->y,TreeMap::new));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java8中Collectors的使用 的相关文章

随机推荐

  • 数据结构Java实现06----中缀表达式转换为后缀表达式

    本文转载至 http www cnblogs com smyhvae p 4790373 html 本文主要内容 表达式的三种形式 中缀表达式与后缀表达式转换算法 一 表达式的三种形式 中缀表达式 运算符放在两个运算对象中间 如 2 1 3
  • 【华为OD机试真题 JS】火锅

    标题 火锅 时间限制 1秒 内存限制 262144K 语言限制 不限 入职后 导师会请你吃饭 你选择了火锅 火锅里会在不同时间下很多菜 不同食材要煮不同的时间 才能变得刚好合适 你希望吃到最多的刚好合适的菜 但是你的手速不够快 用m代表手速
  • [培训-无线通信基础-2]:无线电磁波传播机制(传播、衰减、链路预算)

    作者主页 文火冰糖的硅基工坊 https blog csdn net HiWangWenBing 本文网址 https blog csdn net HiWangWenBing article details 118667807 引言 既然无
  • vue crypto-js加解密

    1 安装crypto js npm install crypto js save 2 编写encrypt js const CryptoJS require crypto js import md5 from js md5 var key
  • 关于程序员【锁死】服务器

    干程序员这么多年 头一次听说 锁死 服务器这么个名词 乍一听到被媒体造的这个名词 觉着很突兀 自己念两遍就会感到头疼 恶心 想吐这么膈应 服务器到底是怎么 锁死 的 什么玩意 你看看人家 数据库系统概论 里面人家关于 锁 的一个翻译 死锁
  • ARM单片机通用IAP在线升级YMODEM协议

    ARM单片机通用IAP在线升级YMODEM协议 效果 YMODEM协议格式 移植修改接口 测试代码 代码获取 效果 YMODEM协议格式 接收开始流程 接收者1HZ发送接收状态 C C 代表字符 C 进入接收状态 发送者发送起始帧 SOH
  • 目标检测学习笔记+附入门资料+表面缺陷检测

    待更新补充 文章目录 放在最前 MARK入门阅读学习资料 一 目标检测基本概念 1 名词含义 目标检测 目标检测方法的分类 Bounding box 滑动窗口 R CNN步骤详解 交并比Interest over Union IoU 平均精
  • 对全连接层(fully connected layer)的通俗理解

    原文地址 https blog csdn net qq 39521554 article details 81385159 定义 全连接层 fully connected layers FC 在整个卷积神经网络中起到 分类器 的作用 如果说
  • matplotlib绘图

    孤影常伴灯 你在夜里写字 我在昏黄中布景 风吹皱那烟波浩渺的迷离 也想吹散关于你的记忆 你在红尘打坐 我在紫陌修佛 万般皆因果 何须嗔叹 闲来无事 索然无趣 忽而兴起 画几个简单的数据分析图 一 将数据生成柱状图 代码 coding utf
  • 【计算机网络】TCP/IP网络模型里这些问题你会吗

    零 为什么需要有TCP IP网络模型 不同设备的进程之间相互通信 需要网络通信 而设备存在多样性 需要兼容各种设备 从而协商出一套通用的网络协议 并且这个网络协议是分层的 每层都有各自的作用和职责 一 最上层是哪层 应用层 1 该层有哪些协
  • SQL 经典面试题:统计最近七天连续三天活跃的用户

    1 需求 给定 mid dt 的用户登录记录表 查找最近 7 天内连续 3 天活跃的用户 id 2 数据表 tmp table tmp login test CREATE TABLE tmp table tmp login test mid
  • 5G UE测量

    目录 系列文章目录 一 为何干测量 二 测量干了啥 三 何时干测量 四 用啥干测量 五 怎么干测量 如 以上就是今天要讲的内容 本文仅仅简单从缘由 结果 时机 原料 过程五个方面概述了5G UE测量大至的来龙去脉 一 为何测量 移动 性管理
  • 【hello Linux】进程信号

    目录 1 进程信号的引出及整体概况 2 信号的产生 1 键盘产生 2 进程异常 3 系统调用 4 软件条件 3 信号的保存 1 信号相关的常见概念 2 sigset t 3 信号集操作函数 4 sigprocmask 对block位图的操作
  • 5.4双积分ADC工作原理

    文章目录 1 高中几个知识点 exp n log n lgx lnx 电容充放电公式 2 双积分型ADC工作原理 3 SAR和 型模数转换器 ADC 1 高中几个知识点 exp n exp函数即指数函数 e的n次方的函数 自然常数e 2 7
  • Java 异常创建及控制

    最近在重新拾起Java 想开始分享一些自己的表达 就从这里开始了 Java中有一个Throwable类 它是所有异常或者说是违例的基础 包括了两种类型的异常 一种叫Error 表示的是编译器和系统错误 我们通常不需要去在意它们 另一种叫Ex
  • 国产版ChatGPT大盘点

    我们看到 最近 国内大厂开始密集发布类ChatGPT产品 一方面 是因为这是最近10年最大的趋势和机会 另一方面 国内的AI 不能别国外卡了脖子 那在类ChatGPT赛道上 哪些中国版的ChatGPT能快速顶上 都各有哪些困境需要突破呢 本
  • 第七周作业1

    1 调试分析课本每一个例题 有可能的话更改成2 3个方法的新程序 2 编程实现课本每一个编程习题 例5 1 include
  • LSM-Tree

    LSM Tree的设计思路是 将数据拆分为几百M大小的Segments 并是顺序写入 它的核心思路其实非常简单 就是假定内存足够大 因此不需要每次有数据更新就必须将数据写入到磁盘中 而可以先将最新的数据驻留在内存中 等到积累到最后多之后 再
  • 递归与迭代

    迭代 迭代 迭代简单来讲就是循环 类比于我们循环输出某一个字符数组时的情景 从字符数组中不断取出字符 再将字符输出 迭代的循环过程则是从栈 或者队列 中不断取出要操作的元素 进行操作 与普通循环过程不同的是在不断取出元素的同时也会向栈中放入
  • Java8中Collectors的使用

    前言 基本类型的流没有这个用法 文章目录 averagingDouble averagingInt averagingLong collectingAndThen counting groupingBy groupingByConcurre