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

How to convert List to Map in Kotlin?

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

val list = listOf("a", "b", "c", "d")

我想将其转换为地图,其中字符串是键。

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

你有两个选择:

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

val map = friends.associateBy({it.facebookId}, {it.points})

第二种,性能较差,是使用标准 map 函数创建 Pair 的列表,toMap 可以使用它来生成最终地图:

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

这在 RC 版本上有所改变。

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

ListMap 使用 associate 函数

在 Kotlin 1.3 中,List 有一个名为 associate 的函数。 associate 有以下声明:

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

Returns a Map containing key-value pairs provided by transform function applied to elements of the given collection.

用法:

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

fun main() {
    val friends = listOf(Person("Sue Helen", 1), Person("JR", 2), Person("Pamela", 3))
    val map = friends.associate({ Pair(it.id, it.name) })
    //val map = friends.associate({ it.id to it.name }) // also works

    println(map) // prints: {1=Sue Helen, 2=JR, 3=Pamela}
}    

ListMap 使用 associateBy 函数

对于 Kotlin,List 有一个名为 associateBy 的函数。 associateBy 具有以下声明:

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

Returns a Map containing the values provided by valueTransform and indexed by keySelector functions applied to elements of the given collection.

用法:

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

fun main() {
    val friends = listOf(Person("Sue Helen", 1), Person("JR", 2), Person("Pamela", 3))
    val map = friends.associateBy(keySelector = { person -> person.id }, valueTransform = { person -> person.name })
    //val map = friends.associateBy({ it.id }, { it.name }) // also works

    println(map) // prints: {1=Sue Helen, 2=JR, 3=Pamela}
}

您可以使用 associate 完成此任务:

val list = listOf("a", "b", "c", "d")
val m: Map<String, Int> = list.associate { it to it.length }

在此示例中,来自 list 的字符串成为键,并且它们对应的长度(作为示例)成为映射内的值。

  • 将可迭代序列元素转换为 kotlin 中的映射,
  • 关联与 associateBy 与 associateWith:

*参考:Kotlin Documentation

1- associate (to set both Keys & Values): 构建一个可以设置键值元素的映射:

IterableSequenceElements.associate { newKey to newValue } //Output => Map {newKey : newValue ,...}

If any of two pairs would have the same key the last one gets added to the map.

The returned map preserves the entry iteration order of the original array.

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

IterableSequenceElements.associateBy { newKey } //Result: => Map {newKey : 'Values will be set  from analogous IterableSequenceElements' ,...}

3- associateWith(通过计算设置Values):构建一个我们可以设置新Values的map,Keys也会设置类似的元素

IterableSequenceElements.associateWith { newValue }  //Result => Map { 'Keys will be set from analogous IterableSequenceElements' : newValue , ...}

来自 Kotlin 技巧的示例:

如果您不想丢失列表中的 重复项,可以使用 groupBy.

来完成此操作

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

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

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}