首页 > 解决方案 > 如何使用 ArrayList 对象 Kotlin 中的 2 个条件进行计数

问题描述

假设我有这个模型课。

data class Bike(
    val bikeId: String? = null,
    val type: String? = null,
    val color: String? = null,
)

如果我想得到 的计数color,我可以使用这个:-

val freqs = list.groupingBy { it.color }.eachCount()

结果将是:-

{GREEN=3, YELLOW=12}

如何计算type还包括在内的地方?

示例结果如下: -

{MOUNTAIN and GREEN=2}
{FOLDING and GREEN=1}

{MOUNTAIN and YELLOW=5}
{FOLDING and YELLOW=1}
{BMX and YELLOW=6}

等等..

标签: kotlin

解决方案


对于每个项目,您需要创建一个包含这两个字段的数据对象。简单Pair就足够了:

list.groupingBy { it.type to it.color }.eachCount()

只是注意it.type to it.color基本相同Pair(it.type, it.color)


推荐阅读