当前位置: 首页 > article >正文

常用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

http://www.kler.cn/a/582553.html

相关文章:

  • jmeter接口测试(三)
  • 前端 - uniapp - - 滚动容器scroll-view实现横向滚动
  • BFS最短路径(十六)127. 单词接龙 困难
  • zabbix报警结合AI进行智能分析
  • 某快餐店用户市场数据挖掘与可视化
  • c++ enum使用笔记
  • RocketMQ 集群架构与部署实践(一)
  • Flutter_学习记录_device_info_plus 插件获取设备信息
  • Java糊涂包(Hutool)的安装教程并进行网络爬虫
  • FreeBSD下安装npm Node.js的22版本 并简单测试js服务器
  • 【Golang】第三弹----运算符
  • Python多版本环境管理UV
  • Linux上位机开发实战(qt编译之谜)
  • Spring 框架面试题集:常见问题解析
  • mysql安装与使用
  • 2024年广州市智能网联汽车创新实践年度报告
  • 文件上传漏洞 upload-labs靶场
  • upload-labs-靶场(1-19关)通关攻略
  • 一次解决Andriod Studio Build Gradle很慢或报错下载失败等问题
  • 蓝桥杯第二天:2023省赛C 1题 分糖果