I have a JSONArray which contains multiple JSONObjects and each JSON object represents a row of data. (Like a SQL row)
Example:
[{
"col1": "c1",
"col2": "r1",
"col3": 12121
}, {
"col1": "c1",
"col2": "r1",
"col3": 1321
}, {
"col1": "c1",
"col2": "r2",
"col3": 4342
}, {
"col1": "c1",
"col2": "r2",
"col3": 4532
}]
A list containing the columns on which group by has to happen:
Example:
["col1","col2"]
Finally, the aggregate that has to be applied, MIN
, MAX
, SUM
, AVG
and also the column on which the aggregate has to be applied:
Expected Output: with aggregate being SUM
[{
"col1": "c1",
"col2": "r1",
"col3": 13442
},{
"col1": "c1",
"col2": "r2",
"col3": 8874
}]
What I have tried so far:
I thought of comparing current with previous with the list of columns that I've whenever I see a change in the value I do an aggregate on that. But This method looks way too inefficient. I was thinking of using Java Streams, but I've very bad at it. Any help would be appreciated.
if (agg.equalsIgnoreCase("MIN")) {
Number min = data.getJSONObject(0).getNumber(column);
for (int i = 0; i < data.length(); i++) {
JSONObject jsonObject = data.getJSONObject(i);
if (i > 1) {
}
}
}