首页 文章

如何在Kotlin中将List转换为Map?

提问于
浏览
88

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

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

我想将它转换为 Map ,其中字符串是键 .

我知道我应该使用.toMap()函数,但我不知道如何,我还没有看到它的任何例子 .

5 回答

  • 21

    你有两个选择:

    第一个也是性能最好的是使用 associateBy 函数,该函数接受两个lambdas来生成键和值,并内联 Map 的创建:

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

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

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

    #1 . 从列表到具有关联功能的 Map

    使用Kotlin, List 有一个名为associate的函数 . associate 有以下声明:

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

    返回包含应用于给定集合元素的transform函数提供的键值对的Map .

    用法:

    class Person(val name: String, val id: Int)
    
    fun main(args: Array<String>) {
        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}
    }
    

    #2 . 使用associateBy函数从List到Map

    使用Kotlin, List 有一个名为associateBy的函数 . associateBy 有以下声明:

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

    返回一个Map,其中包含valueTransform提供的值,并由应用于给定集合元素的keySelector函数索引 .

    用法:

    class Person(val name: String, val id: Int)
    
    fun main(args: Array<String>) {
        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}
    }
    
  • 0

    您可以使用associate执行此任务:

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

    在此示例中, list 中的字符串成为键,其对应的长度(作为示例)成为 Map 内的值 .

  • 3

    RC版本已经改变了 .

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

  • -1

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

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

    并且您需要将其转换为 Map ,其中字符串是键 .

    有两种方法可以做到这一点:

    第一个也是性能最好的是使用associateBy函数,它接受两个lambdas来生成键和值,并内联 Map 的创建:

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

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

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

    资料来源:https://hype.codes/how-convert-list-map-kotlin

相关问题