Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin group by sum of property value in an arraylist

Tags:

android

kotlin

I have an arraylist that contains list of objects like below:

[Activities(id=3116, studentID=5c1a7986c98da061141475b4, actionID=1234, actionName=hohoho, totalPoints=100),
Activities(id=3117, studentID=5c1a7986c98da061141475b4, actionID=4321, actionName=lalala, totalPoints=7),
Activities(id=3118, studentID=5c1a7986c98da061141475b4, actionID=4321, actionName=lalala, totalPoints=4),
Activities(id=3119, studentID=5c1a7986c98da061141475b4, actionID=1234, actionName=hohoho, totalPoints=10)]

Is there any kotlin functions that I can use that can sum the totalPoints based on group actionID from above? If the above arraylist is in sql instead, I can do something like SELECT actionID, SUM(totalPoints) FROM activities GROUP BY actionID, which will return

actionID     totalPoints
1234         110
4321         11
like image 630
imin Avatar asked Mar 02 '23 10:03

imin


1 Answers

If you have the list of activities, then you can get the sum of totalPoints grouping by actionID as below

val result = activities
        .groupBy { it.actionID }
        .mapValues { entry -> entry.value.sumBy { it.totalPoints } }

result would be a map containing the actionID as its key and value as the sum of totalPoints for the respective actionID

Printing result would give

{1234=110, 4321=11}
like image 53
Madhu Bhat Avatar answered Mar 05 '23 00:03

Madhu Bhat