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
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With