Search code examples
javajsonlambdajava-8slamdata

lambda groupingBy Object returns complex JSON


Recently started using the lambda in Java.

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

The above code returns map, which returns out put of rest service as 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}

In the above JSON I have whole Category as key in map, instead I am looking for just the intCatId. So the output will be like

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

Is there any way?

Example:

Domain

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

Category{ int intCatId String CatName ... }

I want to get average of (sum of all expense amounts by category and monthYear) by monthYear.

In above example, rptData is List with sum(fltAmt), monthYear and Category.


Solution

  • Edited as per Shamseer comments


    You almost did it.

    All you need is change the Map<Category, Double> to Map<Integer, Double> and then, in the grouping function, substitute Expense::getCategory for another lambda e -> e.getCategory().getIntCatId() (there is a getter for intCatId, right?)

    This will produce the following output:

    {10013:4134.99,10019:...}