Collections

Kotlin lets you manipulate collections independently of the exact type of objects stored in them. In other words, you add a String to a list of Strings the same way as you would do with Ints or a user-defined class. So, the Kotlin Standard Library offers generic interfaces, classes, and functions for creating, populating, and managing collections of any type.

val numbers = mutableListOf("one", "two", "three", "four")
numbers.add("five")   // this is OK    
//numbers = mutableListOf("six", "seven")   

只讀集合是型變的,可變集合不是型變的
在 Kotlin 中,List 的默認實現(xiàn)是 ArrayList,可以將其視為可調(diào)整大小的數(shù)組

  • 注意,to 符號創(chuàng)建了一個短時存活的 Pair 對象,因此建議僅在性能不重要時才使用它。 為避免過多的內(nèi)存使用,請使用其他方法

可以通過其他集合各種操作的結(jié)果來創(chuàng)建集合

  1. 過濾filter() filterIndexed() filterNot() filterIsInstance() filterNotNull() partition() 檢驗謂詞 any() none() all()
val numbers = listOf("one", "two", "three", "four")
println(numbers.any { it.endsWith("e") })
println(numbers.none { it.endsWith("a") })
println(numbers.all { it.endsWith("e") })

println(emptyList<Int>().all { it > 5 })   // vacuous truth
  1. 映射 map mapIndexed mapNotNull mapIndexedNotNull mapKeys mapValues
  2. 關(guān)聯(lián) associateWith associateBy() 區(qū)別:building maps with collection elements as keys/values
  3. 分組 groupBy()
    5 slice() take() drop() takeWhile()
    6.取單個元素 elementAt() first() last() elementAtOrNull()

雙路合并(zip)

val colors = listOf("red", "brown", "grey")
val animals = listOf("fox", "bear", "wolf")
println(colors zip animals)

val twoAnimals = listOf("fox", "bear")
println(colors.zip(twoAnimals))

集合排序
Most built-in types are comparable: 自定義類型如何排序?
A shorter way to define a Comparator is the compareBy() standard library.
The Kotlin collections package provides functions for sorting collections in natural, custom, and even random orders.
sort read-only collections and sorting mutable collections difference?
sortedBy() sortedWith()
reversed() 返回一個集合(原元素的拷貝),偏好使用asReversed(),如果原集合不變的話.但是,如果如果list的可變行不知道或者原集合就不是list,推薦使用reversed().
隨機順序 shuffled()

集合寫操作
add() addAll() += remvove() removeAll() retainAll() clear() -=(single instance remove the first occurrence of it)

val numbers = mutableListOf("one", "two", "three", "three", "four")
numbers -= "three"
println(numbers)
numbers -= listOf("four", "five")    
//numbers -= listOf("four")    // does the same as above
println(numbers)    

list的操作
getOrElse() getOrNull subList() indexOf() indexOfFirst() binarySearch()
add() addAll() set() fill() removeAt()
set
map plus minus操作

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

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