前端 开发语言 kotlin 过滤集合中的特定的元素 - , &#34

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力网 👁️ 491 次阅读

kotlin提供了过滤集合很方便过滤集合中特定的元素

1 如果是同一种类型的操作,建议使用filter 或者是partition

例如过滤出字符长度大于3的元素 拼多多帮助力入口

使用partition

val numbers = listOf("one", "two", "three", "four")

val (match, rest) = numbers.partition { it.length > 3 }

// 打印结果 [three, four]

Log.d("=======匹配符合条件match", match.toString())

// 打印结果 [one, two]

Log.d("=======匹配不符合条件rest", rest.toString())

使用filter

val numbers = listOf("one", "two", "three", "four")

val langThan3 = numbers.filter { it.length>3 }

如果集合中是不同的类型过滤出相同的类型建议使用filterIsInstance

val numbers = listOf(null, 1, "two", 3.0, "four")

// 过滤出集合中的int

numbers.filterIsInstance().forEach {

// 打印结果是1

Log.d("=======int元素", it.toString())

}

// 过滤出集合中的String

numbers.filterIsInstance().forEach {

// 打印结果是two, four

Log.d("=======String元素", it)

}

推荐文章,前端

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧