Java 8 collect and change the format of the result

Viewed 492

I have the data structre called MyPojo which has fields called time, name and timetaken (all are in Strings). I'm trying to do some grouping as follows:

    List<MyPojo> myPojos = Arrays.asList(
        new MyPojo("2017", "ABC", "30"),
        new MyPojo("2017", "ABC", "20"),
        new MyPojo("2016", "ABC", "25"),
        new MyPojo("2017", "XYZ", "40")
    );

    Map<String, Map<String, Double>> resultMap = myPojos.stream()
        .collect(Collectors.groupingBy(MyPojo::getName,
            Collectors.groupingBy(MyPojo::getTime,
                Collectors.averagingDouble(MyPojo::getTimeTakenAsDouble))));

Please note that I've a method called getTimeTakenAsDouble to convert thetimetaken string to double value.

This results as follows:

    {ABC={2017=25.0, 2016=25.0}, XYZ={2017=40.0}}

However, my frontend developer wanted the data either in the following format:

    {ABC={2017=25.0, 2016=25.0}, XYZ={2017=40.0, 2016=0.0}}

or

    [
            {
                    "time": "2017",
                    "name": "ABC",
                    "avgTimeTaken": 25.0
            },
            {
                    "time": "2017",
                    "name": "XYZ",
                    "avgTimeTaken": 40.0
            },
            {
                    "time": "2016",
                    "name": "ABC",
                    "avgTimeTaken": 25.0
            },
            {
                    "time": "2016",
                    "name": "XYZ",
                    "avgTimeTaken": 0.0
            }
    ]

I'm thinking to perform iterations on the resultMap and prepare the 2nd format. I'm trying to perform the iteration again on the resultMap. Is there any other way to handle this?

1 Answers
Related