Kotlin数组
对于基本类型和String,可以是用xxxArray()创建数组:
1 | val intArray = IntArray(10) |
也可以使用arrayOf()、arrayOfNulls()、emptyArray()进行类型推测:
1 | val intArray = arrayOf(1, 2, 3, 4) |
使用Array(size: Int, init:(Int) -> T),第二个参数可以通过闭包的形式创建数组对象
1 | fun main(args: Array<String>) { |
Kotlin集合
1 | //不可变 |
xxxMapOf<T>()
等价于Java的new xxxMap<T>()
,List和Set也一样。
集合数组操作类
无元素操作符
1
2
3
4
5
6
7
8val list = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
if (list.contains(1)) {
}
list.first()
list.last()
println(list.indexOf(1))
println(list.elementAt(1))
list.single()顺序操作符
1
2
3
4
5
6
7
8
9
10val list = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
list.reversed()
list.sorted()
list.sortedDescending()
list.sortedBy {
it
}
list.sortedByDescending {
it
}映射操作符
1
2
3
4
5
6
7
8
9
10
11val list = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
list.map {
}
list.flatMap { it ->
List(it) {
it * it
}
}
list.groupBy {
it
}过滤操作符
1
2
3
4
5
6
7
8
9
10
11val list = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
// 过滤
list.filter {
it%2==0
}.forEach {
println(it)
}
//获取前三个
list.take(3).forEach { println(it) }
//抛弃前三个
list.drop(3).forEach { println(it) }生产操作符
1
2
3
4
5
6val list = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
list.zip(list).forEach { println(it) }
list.partition {
it%3==0
}.first.forEach { println(it) }
list.plus(100).forEach { print(it) }统计操作符
1
2
3
4
5
6
7
8
9
10
11
12
13val list = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
if (list.any { it==3 }) {
println("yes")
}
if (list.all { it > 0 }) {
println("yes")
}
if (list.none { it < 0 }) {
println("yes")
}
list.max()
list.min()
println(list.sum())