【问题标题】:Using Collectors to GroupBy one field, Count and Add another field value使用收集器对一个字段进行分组,计数并添加另一个字段值
【发布时间】:2019-10-08 20:43:47
【问题描述】:

我想使用收集器来分组一个字段,计算并添加另一个字段的值。例如:

这是我的数据库表:

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

我想要做的是分组结果列,然后计数但也考虑到'numberof'的值。所以在这种情况下,在分组、计数和添加值之后:

"24GB": 4
"10GB": 2

不太清楚怎么做,希望大家帮帮我。

Map<String,Long> statusMap = statusList.stream()
            .collect(Collectors.groupingBy(
                Status::getResult,
                Collectors.counting()));

【问题讨论】:

  • 但是你想在最后得到计数吗?您的输出仅保留当前的总和
  • 是的,我正在计算之后的总数。

标签: java spring java-stream collectors


【解决方案1】:
 Map<String,Long> statusMap = statusList.stream()
        .collect(Collectors.groupingBy(
            Status::getResult,
            Collectors.summingLong(Status::getNumberOf)));

【讨论】:

    猜你喜欢
    • 2022-08-22
    • 2018-07-19
    • 2020-08-13
    • 1970-01-01
    • 2011-09-04
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多