imin
imin

Reputation: 4578

kotlin group by sum of property value in an arraylist

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

Upvotes: 4

Views: 2984

Answers (2)

IR42
IR42

Reputation: 9672

val result = list.groupingBy { it.actionID }
        .fold(0) { acc, element -> acc + element.totalPoints }

groupingBy is kind of lazy groupBy, it doesn't create intermediate collection, therefore, it should be faster than groupBy when we need to do additional actions after grouping. After groupingBy we can use fold to sum elements from the same group.

Upvotes: 4

Madhu Bhat
Madhu Bhat

Reputation: 15173

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}

Upvotes: 5

Related Questions