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)建集合
- 過濾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
- 映射 map mapIndexed mapNotNull mapIndexedNotNull mapKeys mapValues
- 關(guān)聯(lián) associateWith associateBy() 區(qū)別:building maps with collection elements as keys/values
- 分組 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操作