java - Using Collectors to GroupBy one field, Count and Add another field value
问题描述
I would like to use Collectors in order to groupBy one field, count and add the value of another field. For example:
This is my DB Table:
id host result numberof date
23 host1 24GB 1 2019-05-20
23 host7 10GB 1 2019-04-21
23 host3 24GB 3 2019-05-12
23 host4 10GB 1 2019-04-22
What I want to do, is to groupBy result column, then count BUT also take into account the value of 'numberof'. so In this case after grouping, counting and adding the values:
"24GB": 4
"10GB": 2
Not really sure how to do it, I hope you guys can help me out.
Map<String,Long> statusMap = statusList.stream()
.collect(Collectors.groupingBy(
Status::getResult,
Collectors.counting()));
解决方案
Map<String,Long> statusMap = statusList.stream()
.collect(Collectors.groupingBy(
Status::getResult,
Collectors.summingLong(Status::getNumberOf)));
推荐阅读
- batch-file - 批处理文件:将文件名插入文本文件
- powershell - 如何为 Powershell 配置启动/配置脚本?
- c - 如何在c中访问数组内的数组元素?
- scala - 高阶函数定义中的括号错误(Scala)
- spring-boot - spring batch ftp 集成超时错误 - 使用 spring-boot/spring-batch 进行 ETL
- python - 从嵌套循环将输出写入csv?
- c++11 - 在 C++ 中的 std::deque 中将集合的迭代器存储为用户定义的类型
- python - 在 Altair 的分组和堆叠条形图中为每个组使用单独的比例
- c++ - 如何在运行时仅在我的 C++ 项目中重建一个文件来修复 Visual Studio 2019
- python - 如何在scrapy中获取所有具有正确格式的帖子文本?