记录一下常用操作,方便查找
注意区分可变和不可变的声明和使用
| 只读 |
可读写 |
| Collection |
MutableCollection |
| List |
MutableList |
| Set |
MutableSet |
| Map<K, out V> |
MutableMap<K, V> |
list
var myList: MutableList<Int> = mutableListOf<Int>() myList.add(10) myList.remove(10)
val numbers: MutableList<Int> = mutableListOf(1, 2, 3) val readOnlyView: List<Int> = numbers println(numbers) numbers.add(4) println(readOnlyView) readOnlyView.clear()
val strings = hashSetOf("a", "b", "c", "c") assert(strings.size == 3)
|
操作符
val list = listOf(1, 2, 3, 4, 5, 6)
list.any { it >= 0 }
list.all { it >= 0 }
list.none { it < 0 }
list.count { it >= 0 }
|
累计
list.sum()
list.sumBy { it % 2 }
list.fold(100) { accumulator, element -> accumulator + element / 2 }
list.foldRight(100) { accumulator, element -> accumulator + element / 2 }
list.reduce { accumulator, element -> accumulator + element / 2 }
list.reduceRight { accumulator, element -> accumulator + element / 2 }
|
遍历
list.forEach { print(it) }
list.forEachIndexed { index, value -> println("position $index contains a $value") }
|
最大最小
list.max()
list.maxBy { it }
list.min()
list.minBy { it }
|
过滤
list.drop(2)
list.dropLast(2)
list.dropWhile { it > 3 }
list.dropLastWhile { it > 3 }
list.take(2)
list.takeLast(2)
list.takeWhile { it>3 }
list.takeLastWhile { it>3 }
list.filter { it > 3 }
list.filterNot { it > 3 }
list.filterNotNull()
list.slice(listOf(0, 1, 2))
|
映射
list.map { it * 2 }
list.mapIndexed { index, it -> index * it }
list.mapNotNull { it * 2 }
list.flatMap { listOf(it, it + 1) }
list.groupBy { if (it % 2 == 0) "even" else "odd" }
|
以上函数都有一个带to后缀的版本,例如mapTo。mapTo与map的区别是:返回的List是由参数传入的:
val targetList = mutableListOf<Int>() list.mapTo(targetList) { it * 2 }
|
元素
list.contains(2)
list.elementAt(0)
list.elementAtOrNull(10)
list.elementAtOrElse(10) { index -> index * 2 }
list.first()
list.first { it > 1 }
list.firstOrNull()
list.firstOrNull { it > 1 }
list.last() list.last { it > 1 } list.lastOrNull() list.lastOrNull { it > 1 }
list.indexOf(2)
list.lastIndexOf(2)
list.indexOfFirst { it > 2 }
list.indexOfLast { it > 2 }
list.single { it == 5 }
list.singleOrNull { it == 5 }
|
合并,分解
val list = listOf(1, 2, 3, 4, 5, 6) val list2 = listOf(5, 6, 7, 8, 9, 0)
list + list2
val (list3, list4) = list.partition { it % 2 == 0 }
val pairList: List<Pair<Int, Int>> = list.zip(list2)
val (list5, list6) = pairList.unzip()
|
排序
val list = listOf(1, 2, 3, 4, 5, 6)
list.reversed()
list.sorted()
list.sortedBy { it*2 }
list.sortedDescending() list.sortedByDescending { it*2 }
|
set
map