按键列表分组(科特琳)

时间:2020-01-15 10:53:21

标签: kotlin grouping

假设我有一个

class Question(val tags:List<String>, val text:String)

(显然)除其他属性外还具有多个标签。

我想将许多Question实例转换为Question映射的(单个!)标签,例如:Map<String,List<Question>>

我该怎么做?简单的groupBy { it.tags }提供了Map<List<String>,List<Question>>

2 个答案:

答案 0 :(得分:1)

一个通用的扩展功能,正如我几次要求的那样:

fun <T, K> Iterable<T>.groupByMany(
    keyExtractor: (T) -> Iterable<K>
): Map<K, List<T>> = mutableMapOf<K, MutableList<T>>()
    .also { grouping ->
        forEach { item ->
            keyExtractor(item).forEach { key ->
                grouping.computeIfAbsent(key) { mutableListOf() }.add(item)
            }
        }
    }

用法:

val byTag = questions.groupByMany { it.tags }

答案 1 :(得分:0)

val questions: Iterable<Question> = ....
val map = HashMap<String, MutableList<Question>>()
questions.forEach { question ->
    question.tags.forEach { tag ->
        val otherQuestions = map[tag]
        if (otherQuestions == null) map[tag] = arrayListOf(question)
        else otherQuestions.add(question)
    }
}
val resultMap: Map<String, List<Question>> = map