Fork me on GitHub

常用Kotlin方法

前提知识#

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

创建方式 事例 是否可变 说明
arrayListOf() mutableListOf() val array = arrayListOf(1,4,7) 可变 必须制定元素类型
listOf() val array = listOf(1,4,7) 不可变 必须制定元素类型,必须指定初始化数据类型
arrayMap/SetOf() mutableMap/SetOf() val array = arrayMapOf(Pair("k","v")) val set = arrayMapOf(1,2,3) 可变 必须使用Pair包装 ,Set集合会去重
map/setOf() val array = map/arraySetOf(Pair("k","v")) 不可变 必须制定元素类型,必须指定初始化数据类型,Set集合会去重

转换操作符#

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

作者:kevin2022

出处:https://www.cnblogs.com/kevin2022/p/15016622.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

你可以在这里自定义其他内容

posted @   KevinAt2022  阅读(171)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示
more_horiz
keyboard_arrow_up light_mode palette
选择主题
menu