常用Kotlin方法

前提知识

kotlin的集合分为可变和不可变,可变的集合带有mutable形容词。

转换操作符

list转array,set转list,list转MutableList

val sourceList = mutableListOf(1, 2, 3)
val readOnlyCopyList = sourceList.toList() 转为不可变集合

val sourceList = mutableListOf(1, 2, 3)
val copySet = sourceList.toMutableSet() 转为可变Set

映射操作符

  • map
val numbers = setOf(1, 2, 3)
println(numbers.map { it * 3 })
println(numbers.mapIndexed { idx, value -> value * idx })
打印结果
[3, 6, 9]
[0, 2, 6]
  • flatMap
val containers = listOf(
     listOf("one", "two", "three"),
     listOf("four", "five", "six"),
     listOf("seven", "eight")
)
println(containers.flatMap { it.values })
//打印 [one, two, three, four, five, six, seven, eight]

过滤操作符

  • filter
val numbers = listOf("one", "two", "three", "four")
val longerThan3 = numbers.filter { it.length > 3 }
//打印的结果是  three four
  • take
val numbers = listOf("1", "2", "3", "4","5","6")
println(numbers.take(3).toList())
//打印的结果是  1 2 3

val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.take(3)) 保留前三个
println(numbers.takeLast(3)) 保留最后三个
//打印
[one, two, three]
[four, five, six]
  • drop
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.drop(1)) //删除第一个
println(numbers.dropLast(5)) //删除最后5个
//打印
[two, three, four, five, six]
[one]
  • predicates
val numbers = listOf("one", "two", "three", "four")
println(numbers.any { it.endsWith("e") }) //只要有一个以e结尾
println(numbers.none { it.endsWith("a") }) //没有一个以a结尾
println(numbers.all { it.endsWith("e") }) //每一个都是以e结尾
打印结果
true
true
false
  • slice
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.slice(1..3)) //位置以1到3进行打算
println(numbers.slice(0..4 step 2)) //0到4 每次价格2个 0,2,2+2
println(numbers.slice(setOf(3, 5, 0)))
打印结果
[two, three, four]
[one, three, five]
[four, six, one]
  • find
val numbers = listOf(1, 2, 3, 4)
println(numbers.find { it % 2 == 0 }) 找到能被2 整除的数据
println(numbers.findLast { it % 2 == 0 }) 找到最后一个能被2整除的数
打印
2
4

常用Kotlin方法

上一篇:WPA GPU基准测试


下一篇:Querying Microsoft SQL Server 2012 读书笔记:查询和管理XML数据 1 -使用FOR XML返回XML结果集