当前位置: 首页 > news >正文

java8 GroupingBy 用法大全

  java8中,Collectors.groupingBy 会用得比较多,对其常见用法做一个汇总

1,模拟数据

Item

import java.math.BigDecimal;public class Item {private String name;private Integer quantity;private BigDecimal price;public Item(String name, int quantity, BigDecimal price) {this.name = name;this.quantity  = quantity;this.price = price;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getQuantity() {return quantity;}public void setQuantity(Integer quantity) {this.quantity = quantity;}public BigDecimal getPrice() {return price;}public void setPrice(BigDecimal price) {this.price = price;}
}

数据

public static List<Item> initData(){List<Item> items = Arrays.asList(new Item("apple", 20, new BigDecimal("4.99")),new Item("apple", 30, new BigDecimal("7.99")),new Item("apple", 10, new BigDecimal("9.99")),new Item("banana", 30, new BigDecimal("2.99")),new Item("banana", 20, new BigDecimal("6.99")),new Item("orange", 50, new BigDecimal("3.99")),new Item("orange", 20, new BigDecimal("8.99")),new Item("watermelon", 200, new BigDecimal("2.99")),new Item("watermelon", 100, new BigDecimal("5.99")),new Item("kiwi fruit", 40, new BigDecimal("5.88")),new Item("kiwi fruit", 20, new BigDecimal("8.88")));return items;}

2,用法

1,groupingBy

     // 根据水果名称分组private static void groupingBy(){List<Item> items = initData();Map<String, List<Item>> itemGroupBy = ListUtils.emptyIfNull(items).stream()
.collect(Collectors.groupingBy(Item::getName));System.out.println(JSON.toJSONString(itemGroupBy));}

结果:


{"orange": [{"name": "orange","price": 3.99,"quantity": 50}, {"name": "orange","price": 8.99,"quantity": 20}],"banana": [{"name": "banana","price": 2.99,"quantity": 30}, {"name": "banana","price": 6.99,"quantity": 20}],"apple": [{"name": "apple","price": 4.99,"quantity": 20}, {"name": "apple","price": 7.99,"quantity": 30}, {"name": "apple","price": 9.99,"quantity": 10}],"kiwi fruit": [{"name": "kiwi fruit","price": 5.88,"quantity": 40}, {"name": "kiwi fruit","price": 8.88,"quantity": 20}],"watermelon": [{"name": "watermelon","price": 2.99,"quantity": 200}, {"name": "watermelon","price": 5.99,"quantity": 100}]
}

2,groupingCounting

    // 统计水果的种类private static void groupingCounting(){List<Item> items = initData();Map<String, Long> itemGroupCount = ListUtils.emptyIfNull(items).stream()
.collect(Collectors.groupingBy(Item::getName, Collectors.counting()));System.out.println(JSON.toJSONString(itemGroupCount));}

结果

{"orange": 2,"banana": 2,"apple": 3,"kiwi fruit": 2,"watermelon": 2
}

3,groupingSum

    // 统计各水果的总数量private static void groupingSum(){List<Item> items = initData();Map<String, Integer> itemGroupSum = ListUtils.emptyIfNull(items).stream()
.collect(Collectors.groupingBy(Item::getName, 
Collectors.summingInt(Item::getQuantity)));System.out.println(JSON.toJSONString(itemGroupSum));}

结果

{"orange": 70,"banana": 50,"apple": 60,"kiwi fruit": 60,"watermelon": 300
}

 4,groupingMax

     // 统计各水果中数量最多的那个private static void groupingMax(){List<Item> items = initData();Map<String, Item> itemGroupMax = ListUtils.emptyIfNull(items).stream().collect(Collectors.groupingBy(Item::getName,Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparingInt(Item::getQuantity)), Optional::get)));System.out.println(JSON.toJSONString(itemGroupMax));Map<String, Item> itemGroupMaxMap = ListUtils.emptyIfNull(items).stream().collect(Collectors.toMap(Item::getName, Function.identity(), BinaryOperator.maxBy(Comparator.comparingInt(Item::getQuantity))));System.out.println(JSON.toJSONString(itemGroupMaxMap));}

 结果

{"orange": {"name": "orange","price": 3.99,"quantity": 50},"banana": {"name": "banana","price": 2.99,"quantity": 30},"apple": {"name": "apple","price": 7.99,"quantity": 30},"kiwi fruit": {"name": "kiwi fruit","price": 5.88,"quantity": 40},"watermelon": {"name": "watermelon","price": 2.99,"quantity": 200}
}

Collectors.collectingAndThen 聚合后再操作

其参数:

collectingAndThen(Collector<T,A,R> downstream, Function<R,RR> finisher) 

 5,grouping mapping

     // 统计各水果的价格private static void groupingSet(){List<Item> items = initData();Map<String, Set<BigDecimal>> itemGroupSet = ListUtils.emptyIfNull(items).stream()
.collect(Collectors.groupingBy(Item::getName,Collectors.mapping(Item::getPrice, Collectors.toSet())));System.out.println(JSON.toJSONString(itemGroupSet));Map<String, List<BigDecimal>> itemGroupList = ListUtils.emptyIfNull(items).stream()
.collect(Collectors.groupingBy(Item::getName,Collectors.mapping(Item::getPrice, Collectors.toList())));System.out.println(JSON.toJSONString(itemGroupList));}

 结果

{"orange": [3.99, 8.99],"banana": [2.99, 6.99],"apple": [7.99, 9.99, 4.99],"kiwi fruit": [5.88, 8.88],"watermelon": [2.99, 5.99]
}

  6,groupingMap

    // 统计各水果的数量对应价格private static void groupingMap(){List<Item> items = initData();Map<String, Map<Integer, BigDecimal>> itemGroupMap = ListUtils.emptyIfNull(items).stream()
.collect(Collectors.groupingBy(Item::getName,Collectors.toMap(Item::getQuantity, Item::getPrice, (x, y) -> x)));System.out.println(JSON.toJSONString(itemGroupMap));Map<String, Map<Integer, BigDecimal>> itemGroupMap2 = ListUtils.emptyIfNull(items).stream()
.collect(Collectors.groupingBy(Item::getName, Collectors.collectingAndThen(Collectors.toMap(Item::getQuantity, Item::getPrice), v -> v)));System.out.println(JSON.toJSONString(itemGroupMap2));}

  结果

{"orange": {50: 3.99,20: 8.99},"banana": {20: 6.99,30: 2.99},"apple": {20: 4.99,10: 9.99,30: 7.99},"kiwi fruit": {20: 8.88,40: 5.88},"watermelon": {100: 5.99,200: 2.99}
}

第一种更为简便

 7,groupingAvg

    // 统计各水果的平均数量  int double long 三种类型private static void groupingAvg(){List<Item> items = initData();Map<String, Double> itemGroupAvg = ListUtils.emptyIfNull(items).stream().collect(Collectors.groupingBy(Item::getName,Collectors.averagingInt(Item::getQuantity)));System.out.println(JSON.toJSONString(itemGroupAvg));}

  结果

{"orange": 35.0,"banana": 25.0,"apple": 20.0,"kiwi fruit": 30.0,"watermelon": 150.0
}

总结:

   常见使用聚合再进行map处理,用于匹配数据。了解Collectors.collectingAndThen的用法,聚合后再进行操作。写不来,就分两步写,先完成,再优化。

相关文章:

java8 GroupingBy 用法大全

java8中&#xff0c;Collectors.groupingBy 会用得比较多&#xff0c;对其常见用法做一个汇总 1&#xff0c;模拟数据 Item import java.math.BigDecimal;public class Item {private String name;private Integer quantity;private BigDecimal price;public Item(String nam…...

vue_router__WEBPACK_IMPORTED_MODULE_1__.default is not a constructor

你所建立的项目 是 vue2x &#xff0c;但是却下载了 vue-router4x 而 vue-router4x 适用于 vue3x 所以你需要卸载 vue-router4x&#xff0c;重新下载 vue-router3x 卸载&#xff1a; npm uninstall vue-router 安装&#xff1a;(3版本&#xff09; npm i vue-router3...

前端html2canvas和dom-to-image实现截图功能

目录 需求 历劫过程 截图知识点 html2canvas 文档地址 封装 使用教程 dom-to-image-more 文档地址 封装 使用教程 解决跨域问题 以下是我花了大把时间,薅秃头得出来的最终结果, dom-to-image-more截图时间快到可以让复杂的页面仅需2-3S就能完成截图,内容有点多…...

Hadoop平台集群之间Hive表和分区的导出和导入迁移(脚本)

要编写Shell脚本实现两个Hadoop平台集群之间Hive表和分区的导出和导入迁移 你可以使用Hive的EXPORT和IMPORT命令结合Hadoop的DistCp命令。下面是一个示例脚本&#xff1a; #!/bin/bash# 导出源Hive表的数据到HDFS source_hive_table"source_db.source_table" targe…...

Linux C语言实践eBPF

手动编译了解过程 通过对关键步骤make Msamples/bpf的实践&#xff0c;我们已经可以编译出内核源码中提供的ebpf样例。但这还不够我们充分地理解这个编译过程&#xff0c;我们将这编译过程拆解一下&#xff0c;拆解成可以一步步执行的那种&#xff0c;首先是环境准备&#xff…...

垃圾回收标记阶段算法

1.标记阶段的目的 主要是在GC在前&#xff0c;判断出哪些是有用的对象&#xff0c;哪些是需要回收的对象&#xff0c;只有被标记为垃圾对象&#xff0c;GC才会对其进行垃圾回收。判断对象是否为垃圾对象的两种方式&#xff1a;引用计数算法和可达性分析算法。 2.引用计数算法…...

泰晓科技发布 Linux Lab v1.2 正式版

导读近日消息&#xff0c;Linux Lab 是一套用于 Linux 内核学习、开发和测试的即时实验室&#xff0c;官方称其“可以极速搭建和使用&#xff0c;功能强大&#xff0c;用法简单”。 自去年 12 月份发布 Linux Lab v1.1 后&#xff0c;v1.2 正式版目前已经发布于 GitHub 及 Gite…...

王道数据结构-代码实操1(全注解版)

#include<stdio.h>void loveyou(int n){ // 传入参数类型为int型&#xff0c;在此函数中表示为n&#xff1b;返回值类型为void&#xff0c;即没有返回值&#xff1b; int i1; //定义了一个整数型变量i&#xff0c;且只在loveyou函数中有用&#xff1b;while(i…...

flink写入到kafka 大坑解析。

1.kafka能不能发送null消息&#xff1f; 能&#xff01; 2 flink能不能发送null消息到kafka&#xff1f; 不能&#xff01; public static void main(String[] args) throws Exception {StreamExecutionEnvironment env StreamExecutionEnvironment.getExecutionEnvironment(…...

MATLAB算法实战应用案例精讲-【深度学习】预训练模型-Subword

目录 前言 Subword 1. Subword介绍 分词器是做什么的? 为什么需要分词? 分词方法...

【HarmonyOS】实现从视频提取音频并保存到pcm文件功能(API6 Java)

【关键字】 视频提取类Extractor、视频编解码、保存pcm文件 【写在前面】 在使用API6开发HarmonyOS应用时&#xff0c;通常会开发一些音视频媒体功能&#xff0c;这里介绍如何从视频中提取音频保存到pcm文件功能&#xff0c;生成pcm音频文件后&#xff0c;就可使用音频播放类…...

Linux:shell命令运行原理和权限的概念

文章目录 shell和kernelshell的概念和原理Linux的权限文件的权限文件的类型文件的权限管理权限的实战应用 shell和kernel 从狭义上来讲&#xff0c;Linux是一个操作系统&#xff0c;我们叫它叫kernel&#xff0c;意思是核心&#xff0c;核心的意思顾名思义&#xff0c;就是最关…...

Javascript -- 数组prototype方法探究

一、数组prototype方法探究 1、不改变原数组 1. concat() 这个是数组拼接方法&#xff0c;可以将两个数组或多个数组拼接并返回一个包含两个数组或多个数组内容的新数组&#xff0c;不会改变原数组 方法里面理论上可以写入n个参数&#xff0c; const arr [1,2]; var str …...

android stduio 打开工程后直接报Connection refused解决

报错如下:Connection refused 解决方案: 打开gradle-wrapper.properties修改distributionUrl 将: distributionUrlhttp\://localhost/gradle/distributions/gradle-6.5-bin.zip 替换为: distributionUrlhttps\://services.gradle.org/distributions/gradle-6.5-bin.zip 错…...

搜索与图论(一)

一、DFS与BFS 1.1深度优先搜索(DFS) DFS不具有最短性 //排列数字问题 #include<iostream> using namespace std;const int N 10; int n; int path[N]; bool st[N];void dfs(int u) {if(u n){for(int i 0;i < n;i) printf("%d",path[i]);puts("&qu…...

百题千解计划【CSDN每日一练】“小明投篮,罚球线投球可得一分”(附解析+多种实现方法:Python、Java、C、C++、C#、Go、JavaScript)

这个心上人,还不知道在哪里,感觉明天就会出现。 🎯作者主页: 追光者♂🔥 🌸个人简介: 💖[1] 计算机专业硕士研究生💖 🌟[2] 2022年度博客之星人工智能领域TOP4🌟 🏅[3] 阿里云社区特邀专家博主🏅 🏆[4] CSDN-人工智能领域优质创作者�…...

lemon框架开发笔记

lemon框架开发笔记 JudgeUtils.isBlank() 字符串为 null 或者 "" ----返回true JudgeUtils.isNotBlankAll() 字符串全部不为 null 或者 "" ----返回true JudgeUtils.isBlankAll() 字符串全部为 null 或者 "" ----返回true// isBlank 是在isEmpt…...

Spark SQL快速入门

1. 了解Spark SQL 1.1 什么是Spark SQL Spark SQL是spark的一个模块&#xff0c;用于处理海量的结构化数据。 1.2 Spark SQL有什么特点&#xff1f;优点是什么&#xff1f; 特点&#xff1a; Spark SQL支持读取和写入多种格式的数据源&#xff0c;包括Parquet、JSON、CSV、…...

linux+Jenkins+飞书机器人发送通知(带签名)

文章目录 如何使用在linux 上安装python 环境发送消息python脚本把脚本上传倒linux上 jenkins 上执行脚本 如何使用 自定义机器人使用指南飞书官网https://open.feishu.cn/document/client-docs/bot-v3/add-custom-bot 在linux 上安装python 环境 yum install python3 python…...

react hooks

1 useEffect(setup,dependencies) 使用object.is来比较每个依赖项和它先前的值 依赖项为空数组的effect不会在组件任何props和state发生改变时重新运行 当useEffect依赖于外部传入props对象时&#xff0c;容易造成死循环 需要对依赖对象进行深比较 import { isEqual } from…...

简易版抽奖活动的设计技术方案

1.前言 本技术方案旨在设计一套完整且可靠的抽奖活动逻辑,确保抽奖活动能够公平、公正、公开地进行,同时满足高并发访问、数据安全存储与高效处理等需求,为用户提供流畅的抽奖体验,助力业务顺利开展。本方案将涵盖抽奖活动的整体架构设计、核心流程逻辑、关键功能实现以及…...

K8S认证|CKS题库+答案| 11. AppArmor

目录 11. AppArmor 免费获取并激活 CKA_v1.31_模拟系统 题目 开始操作&#xff1a; 1&#xff09;、切换集群 2&#xff09;、切换节点 3&#xff09;、切换到 apparmor 的目录 4&#xff09;、执行 apparmor 策略模块 5&#xff09;、修改 pod 文件 6&#xff09;、…...

关于 WASM:1. WASM 基础原理

一、WASM 简介 1.1 WebAssembly 是什么&#xff1f; WebAssembly&#xff08;WASM&#xff09; 是一种能在现代浏览器中高效运行的二进制指令格式&#xff0c;它不是传统的编程语言&#xff0c;而是一种 低级字节码格式&#xff0c;可由高级语言&#xff08;如 C、C、Rust&am…...

k8s业务程序联调工具-KtConnect

概述 原理 工具作用是建立了一个从本地到集群的单向VPN&#xff0c;根据VPN原理&#xff0c;打通两个内网必然需要借助一个公共中继节点&#xff0c;ktconnect工具巧妙的利用k8s原生的portforward能力&#xff0c;简化了建立连接的过程&#xff0c;apiserver间接起到了中继节…...

OpenLayers 分屏对比(地图联动)

注&#xff1a;当前使用的是 ol 5.3.0 版本&#xff0c;天地图使用的key请到天地图官网申请&#xff0c;并替换为自己的key 地图分屏对比在WebGIS开发中是很常见的功能&#xff0c;和卷帘图层不一样的是&#xff0c;分屏对比是在各个地图中添加相同或者不同的图层进行对比查看。…...

【数据分析】R版IntelliGenes用于生物标志物发现的可解释机器学习

禁止商业或二改转载&#xff0c;仅供自学使用&#xff0c;侵权必究&#xff0c;如需截取部分内容请后台联系作者! 文章目录 介绍流程步骤1. 输入数据2. 特征选择3. 模型训练4. I-Genes 评分计算5. 输出结果 IntelliGenesR 安装包1. 特征选择2. 模型训练和评估3. I-Genes 评分计…...

CSS设置元素的宽度根据其内容自动调整

width: fit-content 是 CSS 中的一个属性值&#xff0c;用于设置元素的宽度根据其内容自动调整&#xff0c;确保宽度刚好容纳内容而不会超出。 效果对比 默认情况&#xff08;width: auto&#xff09;&#xff1a; 块级元素&#xff08;如 <div>&#xff09;会占满父容器…...

音视频——I2S 协议详解

I2S 协议详解 I2S (Inter-IC Sound) 协议是一种串行总线协议&#xff0c;专门用于在数字音频设备之间传输数字音频数据。它由飞利浦&#xff08;Philips&#xff09;公司开发&#xff0c;以其简单、高效和广泛的兼容性而闻名。 1. 信号线 I2S 协议通常使用三根或四根信号线&a…...

LLMs 系列实操科普(1)

写在前面&#xff1a; 本期内容我们继续 Andrej Karpathy 的《How I use LLMs》讲座内容&#xff0c;原视频时长 ~130 分钟&#xff0c;以实操演示主流的一些 LLMs 的使用&#xff0c;由于涉及到实操&#xff0c;实际上并不适合以文字整理&#xff0c;但还是决定尽量整理一份笔…...

C++课设:简易日历程序(支持传统节假日 + 二十四节气 + 个人纪念日管理)

名人说:路漫漫其修远兮,吾将上下而求索。—— 屈原《离骚》 创作者:Code_流苏(CSDN)(一个喜欢古诗词和编程的Coder😊) 专栏介绍:《编程项目实战》 目录 一、为什么要开发一个日历程序?1. 深入理解时间算法2. 练习面向对象设计3. 学习数据结构应用二、核心算法深度解析…...