Search code examples
javajava-streamvert.x

How to access values of JsonObject inside collect operator


Below is an example of getting sum of purchase amounts monthwise by using groupingBy.

Map<Month, Double> monthlySumOfPurchases = purchases
                .stream()
                .collect(Collectors.groupingBy(
                        Purchase::getMonthOfDate, 
                        Collectors.summingDouble(Purchase::getPrice)));

Purchase is a class here, so collector worked for us. Now if I have List of JsonObject (io.vertx.core.json package), so purchases are JsonObjects now. How do I get monthwise sum of purchase amounts using streams now?


Solution

  • Approach 1

    The simplest thing you can do is to first convert each of those JSONObject to instances of Purchase and then your collector remains same.

    Approach 2

    As an alternative you can also try something like this:

    Map<Month, Double> monthlySumOfPurchases = purchases
                    .stream()
                    .collect(Collectors.groupingBy(jsonObject->
                            jsonObject.getInteger("month_instant"), 
    Collectors.summingDouble(jsonObj -> jsonObj.getDouble("price"))));
    

    I have assumed here your month_instant and price to be Integer and Double respectively due to lack of that information in question. However, you can modify them according to your own data.

    You can try both these approaches. However, the first approach is simpler and more straightforward to implement.