一切皆是映射:詳解 Kotlin Map 集合類

时间:2022-07-23
本文章向大家介绍一切皆是映射:詳解 Kotlin Map 集合類,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

map's size

var mp = mapOf(1 to "aone", 2 to "two", 3 to "three")
println(mp.size) // 3

get key value

println(mp[2]) // two

for iterator

    for ((k, v) in mp) {
        println("$k->$v")
    }

//    1->aone
//    2->two
//    3->three

forEach iterator

    mp.forEach { k, v ->
        println("$k->$v")
    }

//    1 -> aone
//    2 -> two
//    3 -> three

map function

//    1 -> aone
//    2 -> two
//    3 -> three

    mp.map {
        println("${it.key} -> ${it.value}")
    }

//    1 -> aone
//    2 -> two
//    3 -> three

    mp.keys.map {
        println("$it")
    }

//    1
//    2
//    3

    mp.values.map {
        println("$it")
    }

//    aone
//    two
//    three

containsKey, containsValue

    val containsKey1 = mp.containsKey(1)
    println("containsKey1=$containsKey1") // containsKey1=true

    val containsValue = mp.containsValue("four")
    println("containsValue=$containsValue") // containsValue=false

isNotEmpty

    val isNotEmpty = mp.isNotEmpty()
    println("isNotEmpty=$isNotEmpty") // isNotEmpty=true

sort map

    val mmp = mapOf(1 to "aone", 3 to "three", 2 to "two", 4 to "four")
    val sortedMap: SortedMap<Int, String> = mmp.toSortedMap(Comparator { o1, o2 ->
        println("o1=$o1,o2=$o2")
        if (o1 > o2) 1 else if (o1 < o2) -1 else 0
    })

    println(sortedMap) //    {1=aone, 2=two, 3=three, 4=four}

Convert Map to List

    val keyList = ArrayList(mmp.keys)
    val valueList = ArrayList(mmp.values)

    println("Key List: $keyList") //    Key List: [1, 3, 2, 4]
    println("Value List: $valueList") //    Value List: [aone, three, two, four]


    val list = mmp.toList().map { "${it.first}_${it.second}" }
    println("list=$list") // list=[1_aone, 3_three, 2_two, 4_four]

Kotlin transform Map keys

   var bzkMap: Map<Int, String> = mapOf(0 to "zero", 1 to "one", 2 to "two", 3 to "three")

    var keysMap = bzkMap.mapKeys { it.key * 100 }

    println(keysMap)

    var newKeysMap = mutableMapOf<Int, String>()

    bzkMap.mapKeysTo(newKeysMap) { it.key * 1000 }

    println(newKeysMap)

Kotlin transform Map Values

    var valuesMap = bzkMap.mapValues { it.value.toUpperCase() }

    println(valuesMap)

    var newValuesMap = mutableMapOf<Int, String>()

    bzkMap.mapValuesTo(newValuesMap) { "_${it.value.toUpperCase()}_" }

    println(newValuesMap)

Converting a List to Map in Kotlin

    val user1 = User("John", 18, listOf("Hiking", "Running", "Reading"))
    val user2 = User("Sara", 25, listOf("Chess", "Music"))
    val user3 = User("Dave", 34, listOf("Games", "Programming"))

    val myList = listOf(user1, user2, user3)

    val myMap = myList.map { it.name to it }.toMap()

    println(myMap) // {John=User(name=John, age=18, hobbit=[Hiking, Running, Reading]), Sara=User(name=Sara, age=25, hobbit=[Chess, Music]), Dave=User(name=Dave, age=34, hobbit=[Games, Programming])}

The associateTo Method

    val amap = myList.associateBy { it.age }
    println(amap) // {18=User(name=John, age=18, hobbit=[Hiking, Running, Reading]), 25=User(name=Sara, age=25, hobbit=[Chess, Music]), 34=User(name=Dave, age=34, hobbit=[Games, Programming])}

源代碼:

package k

import java.util.*
import kotlin.Comparator

/**
 * Map is nothing but a key-value pair mappings, every in the map a has a value and every value has a key.
 *
 * @author: Jack
 * 2020-08-19 00:22
 */

fun main(args: Array<String>) {
    var mp = mapOf(1 to "aone", 2 to "two", 3 to "three")

    // map's size
    println(mp.size) // 3

    // get key value
    println(mp[2]) // two

    // for iterator
    for ((k, v) in mp) {
        println("$k->$v")
    }

//    1->aone
//    2->two
//    3->three

    // forEach iterator
    mp.forEach { k, v ->
        println("$k->$v")
    }

//    1 -> aone
//    2 -> two
//    3 -> three

    mp.map {
        println("${it.key} -> ${it.value}")
    }

//    1 -> aone
//    2 -> two
//    3 -> three

    mp.keys.map {
        println("$it")
    }

//    1
//    2
//    3

    mp.values.map {
        println("$it")
    }

//    aone
//    two
//    three

    val containsKey1 = mp.containsKey(1)
    println("containsKey1=$containsKey1") // containsKey1=true

    val containsValue = mp.containsValue("four")
    println("containsValue=$containsValue") // containsValue=false

    val isNotEmpty = mp.isNotEmpty()
    println("isNotEmpty=$isNotEmpty") // isNotEmpty=true

    // sort map
    val mmp = mapOf(1 to "aone", 3 to "three", 2 to "two", 4 to "four")
    val sortedMap: SortedMap<Int, String> = mmp.toSortedMap(Comparator { o1, o2 ->
        println("o1=$o1,o2=$o2")
        if (o1 > o2) 1 else if (o1 < o2) -1 else 0
    })

    println(sortedMap) //    {1=aone, 2=two, 3=three, 4=four}

//    o1=1,o2=1
//    o1=3,o2=1
//    o1=2,o2=1
//    o1=2,o2=3
//    o1=4,o2=2
//    o1=4,o2=3


    // Convert Map to List
    val keyList = ArrayList(mmp.keys)
    val valueList = ArrayList(mmp.values)

    println("Key List: $keyList") //    Key List: [1, 3, 2, 4]
    println("Value List: $valueList") //    Value List: [aone, three, two, four]


    val list = mmp.toList().map { "${it.first}_${it.second}" }
    println("list=$list") // list=[1_aone, 3_three, 2_two, 4_four]

    // Kotlin transform Map keys

    var bzkMap: Map<Int, String> = mapOf(0 to "zero", 1 to "one", 2 to "two", 3 to "three")

    var keysMap = bzkMap.mapKeys { it.key * 100 }

    println(keysMap)

    var newKeysMap = mutableMapOf<Int, String>()

    bzkMap.mapKeysTo(newKeysMap) { it.key * 1000 }

    println(newKeysMap)


    // Kotlin transform Map Values

    var valuesMap = bzkMap.mapValues { it.value.toUpperCase() }

    println(valuesMap)

    var newValuesMap = mutableMapOf<Int, String>()

    bzkMap.mapValuesTo(newValuesMap) { "_${it.value.toUpperCase()}_" }

    println(newValuesMap)


    // Converting a List to Map in Kotlin

    val user1 = User("John", 18, listOf("Hiking", "Running", "Reading"))
    val user2 = User("Sara", 25, listOf("Chess", "Music"))
    val user3 = User("Dave", 34, listOf("Games", "Programming"))

    val myList = listOf(user1, user2, user3)

    val myMap = myList.map { it.name to it }.toMap()

    println(myMap) // {John=User(name=John, age=18, hobbit=[Hiking, Running, Reading]), Sara=User(name=Sara, age=25, hobbit=[Chess, Music]), Dave=User(name=Dave, age=34, hobbit=[Games, Programming])}

    // The associateTo Method
    val amap = myList.associateBy { it.age }
    println(amap) // {18=User(name=John, age=18, hobbit=[Hiking, Running, Reading]), 25=User(name=Sara, age=25, hobbit=[Chess, Music]), 34=User(name=Dave, age=34, hobbit=[Games, Programming])}


}

data class User(val name: String, val age: Int, val hobbit: List<String>)

/**
Outputs:

3
two
1->aone
2->two
3->three
1->aone
2->two
3->three
1 -> aone
2 -> two
3 -> three
1
2
3
aone
two
three
containsKey1=true
containsValue=false
isNotEmpty=true
o1=1,o2=1
o1=3,o2=1
o1=2,o2=1
o1=2,o2=3
o1=4,o2=2
o1=4,o2=3
{1=aone, 2=two, 3=three, 4=four}
Key List: [1, 3, 2, 4]
Value List: [aone, three, two, four]
list=[1_aone, 3_three, 2_two, 4_four]
{0=zero, 100=one, 200=two, 300=three}
{0=zero, 1000=one, 2000=two, 3000=three}
{0=ZERO, 1=ONE, 2=TWO, 3=THREE}
{0=_ZERO_, 1=_ONE_, 2=_TWO_, 3=_THREE_}
{John=User(name=John, age=18, hobbit=[Hiking, Running, Reading]), Sara=User(name=Sara, age=25, hobbit=[Chess, Music]), Dave=User(name=Dave, age=34, hobbit=[Games, Programming])}
 */


/**
Ref:

https://www.techiedelight.com/convert-map-to-list-kotlin/
https://bezkoder.com/kotlin-map-transform/
https://www.baeldung.com/kotlin-list-to-map
https://stackoverflow.com/questions/37464679/how-to-work-with-maps-in-kotlin
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map-of.html
https://kotlinlang.org/docs/reference/map-operations.html
 
 **/

Ref:

https://www.techiedelight.com/convert-map-to-list-kotlin/ https://bezkoder.com/kotlin-map-transform/ https://www.baeldung.com/kotlin-list-to-map https://stackoverflow.com/questions/37464679/how-to-work-with-maps-in-kotlin https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map-of.html https://kotlinlang.org/docs/reference/map-operations.html