使用对列表,想要将它们转换为集合映射。
输入:对列表是这样的
listOf(Pair('bob', UGLY), Pair('sue', PETTY), Pair('bob', FAT))
所需的输出是集合的映射,其中键是对的
first
,集合是second
mapOf('bob' to setOf(UGLY, FAT), 'sue' to setOf(PETTY))
我已经尝试过这个,但是哇,这太冗长了。这个可以减少吗?
fun main(args: Array<String>) {
var m = HashMap<Int, MutableSet<Int>>()
listOf(1 to 1, 2 to 2, 1 to 3).map {
val set = m.getOrPut(it.first, { listOf<Int>().toMutableSet() })
set.add(it.second)
set
}
println (m)
}
-> {1=[1, 3], 2=[2]}
// yet another version, yields the correct result, but I feel a lack of clarity
// that maybe I'm missing a library function that would suit the purpose.
listOf(1 to 1, 2 to 2, 1 to 3).fold(m, {
mapSet, pair ->
val set = mapSet.getOrPut(pair.first, { listOf<Int>().toMutableSet() })
set.add(pair.second)
mapSet
})
-> {1=[1, 3], 2=[2]}
您可以使用
groupBy
,然后使用 mapValues
,如下所示:
val pairs = listOf(Pair("bob", "UGLY"), Pair("sue", "PETTY"), Pair("bob", "FAT"))
val result = pairs
.groupBy { it.first }
.mapValues { it.value.map { p -> p.second }.toSet() }