我有一个包含对象列表的数组列表,如下所示:

[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)]

是否有任何我可以使用的 kotlin 函数可以根据上面的组 totalPointsactionID 求和?如果上面的数组列表在 sql 中,我可以执行类似 SELECT actionID, SUM(totalPoints) FROM activities GROUP BY actionID 的操作,它会返回
actionID     totalPoints
1234         110
4321         11

最佳答案

如果你有 activities 的列表,那么你可以通过 totalPoints 得到 actionID 分组的总和,如下所示

val result = activities
        .groupBy { it.actionID }
        .mapValues { entry -> entry.value.sumBy { it.totalPoints } }
result 将是包含 actionID 作为其键和值作为相应 totalPointsactionID 总和的映射

打印 result 会给
{1234=110, 4321=11}

10-08 14:57