本文首发于公众号“AntDream”,欢迎微信搜索“AntDream”或扫描文章底部二维码关注,和我一起每天进步一点点
list
创建和修改
不可变list,listOf
var list = listOf("a","d","f")
println(list.getOrElse(3){"Unknown"})
println(list.getOrNull(3) ?: "Unknown")
创建和修改可变list,mutableList
val mutableList = mutableListOf("a","d","f")
mutableList.removeIf { it.contains("a") }
遍历和解构
forIn,forEach,forEachIndexed
用下划线_来跳过不需要的元素
for (s in list){
println(s)
}
list.forEach{
println(it)
}
list.forEachIndexed { index, item ->
println("$index, $item")
}
//解构
val(a,_,c) = list
"_"表示跳过这个元素,跳过的元素不会被读取
转换
list.toMutableList()
去重
list.distinct()
快速筛选和排序
可以结合filter、forEach、sortedByDescending、sortedBy来快速对一个list进行筛选和排序
val resultList = mutableListOf<AppInfo>()
val recommendations = listOf(AppA(), AppB(), AppC())
//根据app的安装时间按照倒序排列
recommendations.filter {
//filter里跟筛选的条件,符合条件的数据会继续走后面的排序
it.isAppInstalled()
}
.sortedByDescending {
//这里是排序的条件,sortedBy是正序
it.getAppInstalledTime()
}.forEach { resultList.add(it) }
set
不可重复的,去重里面的元素,函数操作基本同list
map
fun main() {
val map = mapOf("Jack" to 20, "Jim" to 18)
mapOf(Pair("Jim",20), Pair("json",30))
println(map["Jack"])
println(map.getValue("Jack"))
println(map.getOrElse("java"){"unknown"})
println(map.getOrDefault("java", 0))
map.forEach{
println("${it.key}, ${it.value}")
}
val mutableMap = mutableMapOf("Jack" to 20, "Jim" to 18)
//添加元素
mutableMap += "jim" to 30
mutableMap["jim"] = 31
mutableMap.getOrPut("role"){19}
println(mutableMap)
}
to,实际上是一个函数,返回一个Pair结果
去重
val clone = filteredDirectories.clone() as ArrayList<Directory>
//数据去重。
callback(clone.distinctBy { it.path.getDistinctPath() } as ArrayList<Directory>)
欢迎关注我的公众号查看更多精彩文章!