Dictionary 如何在Kotlin中将列表转换为地图?

Dictionary 如何在Kotlin中将列表转换为地图?,dictionary,kotlin,Dictionary,Kotlin,例如,我有一个字符串列表,如: val list = listOf("a", "b", "c", "d") 我想把它转换成一个映射,其中字符串是键 我知道我应该使用.toMap()函数,但我不知道如何使用,而且我还没有看到任何示例。您有两个选择: 第一个也是最有效的方法是使用associateBy函数,该函数使用两个lambda来生成键和值,并内联创建映射: val map = friends.associateBy({it.facebookId}, {it.points}) 第二个性能较差

例如,我有一个字符串列表,如:

val list = listOf("a", "b", "c", "d")
我想把它转换成一个映射,其中字符串是键

我知道我应该使用
.toMap()
函数,但我不知道如何使用,而且我还没有看到任何示例。

您有两个选择:

第一个也是最有效的方法是使用
associateBy
函数,该函数使用两个lambda来生成键和值,并内联创建映射:

val map = friends.associateBy({it.facebookId}, {it.points})
第二个性能较差的方法是使用标准的
map
函数创建
对的列表,该列表可由
toMap
用于生成最终的映射:

val map = friends.map { it.facebookId to it.points }.toMap()

在RC版本上发生了更改

我正在使用
val map=list.groupByTo(destinationMap,{it.facebookId},{it->it.point})

list
map
关联
函数 在Kotlin 1.3中,
List
有一个名为的函数<代码>关联
具有以下声明:

fun <T, K, V> Iterable<T>.associate(transform: (T) -> Pair<K, V>): Map<K, V>
fun <T, K, V> Iterable<T>.associateBy(keySelector: (T) -> K, valueTransform: (T) -> V): Map<K, V>

列表
映射
,使用
关联功能
有了Kotlin,
List
有一个名为的函数
associateBy
具有以下声明:

fun <T, K, V> Iterable<T>.associate(transform: (T) -> Pair<K, V>): Map<K, V>
fun <T, K, V> Iterable<T>.associateBy(keySelector: (T) -> K, valueTransform: (T) -> V): Map<K, V>
您可以为此任务使用:

val list = listOf("a", "b", "c", "d")
val m: Map<String, Int> = list.associate { it to it.length }
val list=listOf(“a”、“b”、“c”、“d”)
val m:Map=list.associate{it to it.length}
在本例中,
list
中的字符串成为键,其相应的长度(例如)成为映射内的值。

  • 将可迭代序列元素转换为kotlin中的映射
  • 关联vs associateBy vs associated with:
*参考:

1-关联(设置键和值):构建可以设置键和值元素的映射:

IterableSequenceElements.associate { newKey to newValue } //Output => Map {newKey : newValue ,...}
如果两对中的任何一对具有相同的密钥,则最后一对将添加到映射中

返回的映射保留原始数组的条目迭代顺序

2-associateBy(仅通过计算设置键):构建一个地图,我们可以设置新键,类似的元素将被设置为值

IterableSequenceElements.associateBy { newKey } //Result: => Map {newKey : 'Values will be set  from analogous IterableSequenceElements' ,...}
3-associateWith(仅通过计算设置值):构建一个地图,我们可以设置新值,类似的元素将为键设置

IterableSequenceElements.associateWith { newValue }  //Result => Map { 'Keys will be set from analogous IterableSequenceElements' : newValue , ...}
Kotlin tips中的示例:

如果您的列表中有不想丢失的重复项,您可以使用
groupBy
执行此操作

否则,像其他人所说的那样,使用
associate/By/With
(我相信,在重复的情况下,它只会返回带有该键的最后一个值)

按年龄对人员列表进行分组的示例:

class Person(val name: String, val age: Int)

fun main() {
    val people = listOf(Person("Sue Helen", 31), Person("JR", 25), Person("Pamela", 31))

    val duplicatesKept = people.groupBy { it.age }
    val duplicatesLost = people.associateBy({ it.age }, { it })

    println(duplicatesKept)
    println(duplicatesLost)
}
结果:

{31=[Person@41629346, Person@4eec7777], 25=[Person@3b07d329]}
{31=Person@4eec7777, 25=Person@3b07d329}

非常感谢。是因为它创建了一个映射,而不是像我的示例中那样将对列表转换为映射,所以速度更快吗?@lordScone确切地说,
Pair
实例的分配对于大型集合来说可能非常昂贵associateBy和associateBy之间的区别是什么?考虑到它们产生相同的结果,我是否更愿意使用一个而不是另一个?