最近开始在Java中使用lambda。

Map<Category, Double> lMap = rptData.stream().collect(Collectors.groupingBy(Expense::getCategory,
            Collectors.summingDouble(j -> j.getFltAmt().doubleValue())));


上面的代码返回map,该地图以JSON形式返回其余服务。

{"Category(intCatId=10013, strCatName=Home Maint)":4134.99,"Category(intCatId=10019, strCatName=Lease Breakage)":2600.0,"Category(intCatId=10011, strCatName=Utility Bill)":2067.76,"Category(intCatId=10010, strCatName=Fuel)":1018.77,"Category(intCatId=10012, strCatName=Entertainment)":192.4,"Category(intCatId=6, strCatName=Shopping)":1528.25,"Category(intCatId=4, strCatName=Medicine)":128.55,"Category(intCatId=10021, strCatName=Interest)":24.61,"Category(intCatId=3, strCatName=Phone)":539.09,"Category(intCatId=10020, strCatName=Movers)":1350.0,"Category(intCatId=5, strCatName=Grocery)":3519.83,"Category(intCatId=8, strCatName=School)":311.0,"Category(intCatId=10009, strCatName=Insurance)":1117.75,"Category(intCatId=7, strCatName=Eating Out)":614.22,"Category(intCatId=1, strCatName=Vehicle)":2843.58,"Category(intCatId=10018, strCatName=Courier)":22.65,"Category(intCatId=2, strCatName=Rent)":16506.95,"TotCount":13.0,"Category(intCatId=10017, strCatName=Travel)":800.42,"Category(intCatId=10015, strCatName=Donation)":326.0}


在上面的JSON中,我将整个类别作为地图中的键,而我只是在寻找intCatId。所以输出会像

{"10013":4134.99,"10019":...}


有什么办法吗?

例:



费用{
Double fltAmt
日期dtDate
(公式为“ month(dtDate)-year(dtDate)”)
字符串月份
(由intCatId加入)
类别类别
...
}

类别{
int intCatId
字符串猫名
...
}

我想按monthYear获得平均值(按类别和monthYear计算的所有费用金额之和)。

在上面的示例中,rptData是具有sum(fltAmt),monthYear和Category的列表。

最佳答案

根据Shamseer评论进行编辑



您几乎做到了。

您所需要做的就是将Map<Category, Double>更改为Map<Integer, Double>,然后在分组功能中,将Expense::getCategory替换为另一个lambda e -> e.getCategory().getIntCatId()(有intCatId的吸气剂,对吗?)

这将产生以下输出:


  {10013:4134.99,10019:...}

07-24 09:26