如何根据结果分组创建新对象 [英] How do I create a new object from grouping by result

查看:119
本文介绍了如何根据结果分组创建新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于总结之后,我需要创建一个Sales类型的新对象,其总和(group by的总和)如下所示

After summing up, I need to create a new object of Sales type, having the totals ( sum result of group by ) Something like below

{
"month" : "Total",
"year":  "2000",
"state" : "State1",
"city" :  "City1",
"sales" : "15"
}

所以我在Sales中创建了相应的构造函数并尝试了

So i have created corresponding constructor in Sales and tried

list.stream()
    .collect(groupingBy(Sale::getState,
                        groupingBy(Sale::getCity,
                                   summingInt(Sale::getSales).Collectors.mapping(e -> new Sales ("Total","2000","State1","City1",<summingInt result should come here>),
                                Collectors.toList()))));  

如何在Java 8中实现上述格式?

How do I achieve something like above format in Java 8 ?

推荐答案

您可以这样做:

可以将toMap收集器与合并功能一起使用,而不是第二个groupingBy.

instead of second groupingBy you can use toMap collector with merge function.

list.stream()
    .collect(Collectors.groupingBy(Sales::getState,
        Collectors.toMap(Sales::getCity,Function.identity(),                              
              (s1, s2) -> new Sales(s1.month,...,s1.getSales() + s2.getSales()))));

这篇关于如何根据结果分组创建新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆