本文会介绍一些 Kotlin 集合函数,这些函数可以极大地提高我们的开发效率,可以作为小抄随时翻阅~
删除array中重复的字符串
有很多方式可以从数组里移除重复的字符串:
// 保留元素的原始顺序
val devs = arrayOf("Amit", "Ali", "Amit", "Sumit", "Sumit", "Himanshu")
print(devs.distinct()) // [Amit, Ali, Sumit, Himanshu]
// 保留元素的原始顺序
val devs = arrayOf("Amit", "Ali", "Amit", "Sumit", "Sumit", "Himanshu")
print(devs.toSet()) // [Amit, Ali, Sumit, Himanshu]
// 保留元素的原始顺序
val devs = arrayOf("Amit", "Ali", "Amit", "Sumit", "Sumit", "Himanshu")
print(devs.toMutableSet()) // [Amit, Ali, Sumit, Himanshu]
// 不保留元素的原始顺序
val devs = arrayOf("Amit", "Ali", "Amit", "Sumit", "Sumit", "Himanshu")
print(devs.toHashSet()) // [Amit, Ali, Sumit, Himanshu]
**将array 转为 list 或者 string **
你可以使用joinToString
函数将 list 转为字符串。例如, 有一个城市列表(Delhi, Mumbai, Bangalore),,然后你可以把列表转为这样的字符串: “India is one the best country for tourism. You can visit Delhi, Mumbai, Bangalore, etc, and enjoy your holidays”.
val someKotlinCollectionFunctions = listOf(
"distinct", "map",
"isEmpty", "contains",
"filter", "first",
"last", "reduce",
"single", "joinToString"
)
val message = someKotlinCollectionFunctions.joinToString(
separator = ", ",
prefix = "Kotlin has many collection functions like: ",
postfix = "and they are awesome.",
limit = 3,
truncated = "etc "
)
print(message)
Kotlin 还有很多很棒的函数,比如 distinct, map, isEmpty, 等等
把一个集合转为单个结果
如果你想把一个给定的集合转换为单个结果,可以使用 rudece
函数。例如你可以对列表里所有元素求和:
val numList = listOf(1, 2, 3, 4, 5)
val result = numList.reduce {
result, item ->
result + item
}
print(result) // 15
// 注意:如果列表是空的,会抛出RuntimeException
判断所有元素是否满足特定条件
如果你有一个数组或者列表,你想了解其中的所有元素是否全部满足某个条件,可以使用all
函数:
data class User(val id: Int, val name: String, val isCricketLover: Boolean, val isFootballLover: Boolean)
val user1 = User(id = 1, name = "Amit", isCricketLover = true, isFootballLover =