2

最近开始在 Java 中使用 lambda。

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

上面的代码返回 map,它以 JSON 形式返回 out of rest 服务。

{"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 中,我将整个 Category 作为 map 中的键,而我只是在寻找 intCatId。所以输出会像

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

有什么办法吗?

例子:

领域

费用{ Double fltAmt Date dtDate (formula "month(dtDate) - year(dtDate)") String monthYear (joinedby intCatId) Category category ... }

类别{ int intCatId String CatName ... }

我想按月年获得(按类别和月年的所有费用金额的总和)的平均值。

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

4

2 回答 2

1

根据 Shamseer 评论编辑


你几乎做到了。

您只需要更改Map<Category, Double>toMap<Integer, Double>然后在分组函数中替换Expense::getCategory另一个 lambda e -> e.getCategory().getIntCatId()(intCatId 有一个 getter,对吗?)

这将产生以下输出:

{10013:4134.99,10019:...}

于 2017-01-16T07:06:09.427 回答
0

由于您的地图包含作为 Category 对象的键,因此输出 JSON 中存在相同的内容,因为您使用的序列化程序正在将 Category 对象转换为 JSON ......

您可以做的是为类别对象编写一个自定义序列化程序,该序列化程序将返回类别 ID 作为其相应的 JSON 值.....需要有关您正在使用的序列化程序的更多详细信息,以进一步展示如何创建自定义序列化程序。

或者另一种方法是更改​​地图的类型并使用 CategoryId(String type) 作为键....

于 2017-01-15T13:16:23.633 回答