《Kotlin入門實(shí)戰(zhàn)》CH7 | 集合類

集合類

在Java類庫中有一套相當(dāng)完整的容器集合類來持有對象。Kotlin沒有去重復(fù)造輪子(Scala則是自己實(shí)現(xiàn)了一套集合類框架),而是在Java類庫的基礎(chǔ)上進(jìn)行了改造和擴(kuò)展,引入了不可變集合類,同時(shí)擴(kuò)展了大量方便實(shí)用的功能,這些功能的API都在kotlin.collections包下面。

集合類概述

集合層次
  • Iterable 可遍歷
  • MutableIterable 支持刪除元素的迭代
  • List/Set/Map,只讀不可變
  • MutableList/MutableSet/MutableMap,可讀寫

創(chuàng)建集合類

  • listOf/setOf/mapOf 創(chuàng)建不可變集合
  • mutableListOf()、mutableSetOf()、mutableMapOf() 創(chuàng)建可變集合

遍歷集合中的元素

List、Set類繼承了Iterable接口,里面擴(kuò)展了forEach函數(shù)來迭代遍歷元素;同樣,Map接口中也擴(kuò)展了forEach函數(shù)來迭代遍歷元素。

fun main() {
    val list = listOf<Int>(1, 2, 3, 4)
    list.forEach { println(it) }
    list.forEachIndexed { index, i -> println(list[index]) }

    val set = setOf<Int>(1, 2, 3, 4)
    set.forEach { println(it) }
    set.forEachIndexed { index, i -> println("index:$index, i:$i") }

    val map = mapOf(1 to 'A', 2 to 'B', 3 to 'C')
    map.forEach { t, u -> println("Key:$t, value:$u") }
    map.entries.forEach { println(it) }
}
1
2
3
4
1
2
3
4

1
2
3
4
index:0, i:1
index:1, i:2
index:2, i:3
index:3, i:4

Key:1, value:A
Key:2, value:B
Key:3, value:C
1=A
2=B
3=C

映射函數(shù)

使用map函數(shù),可以把集合中的元素依次使用給定的轉(zhuǎn)換函數(shù)進(jìn)行映射操作,元素映射之后的新值會(huì)存入一個(gè)新的集合中,并返回這個(gè)新集合。

fun main() {
    val list = listOf(1, 2, 3, 4)
    val list2 = list.map { it * it }
    val list3 = list.map { it -> listOf(it + 1, it + 2, it + 3, it + 4) }

    println(list2)
    println(list3)
    println(list3.flatten()) // Iterator<Iterator> 類型才能flatten
    list.flatMap { it -> listOf(it + 1, it + 2, it + 3, it + 4) } // 相當(dāng)于map + flatten

}

[1, 4, 9, 16]
[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]]
[2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7, 5, 6, 7, 8]
[2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7, 5, 6, 7, 8]

過濾函數(shù)

val list = listOf(1,2,3,4)
list.filter{ it >= 2 }

排序函數(shù)

    list.reversed()
    list.sorted()

實(shí)際上直接調(diào)用Java Api

去重函數(shù)

val dupList = listOf(1, 1, 2, 2, 3, 3, 3)
dupList.distinct() //去重函數(shù),返回 [1, 2, 3]

http://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/index.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容