ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

kotlin 过滤集合中的特定的元素

2026/9/26 20:41:57 拓冰建站 浏览量
kotlin 过滤集合中的特定的元素

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")// 过滤出集合中的intnumbers.filterIsInstance<Int>().forEach {// 打印结果是1Log.d("=======int元素", it.toString())}// 过滤出集合中的Stringnumbers.filterIsInstance<String>().forEach {// 打印结果是two, fourLog.d("=======String元素", it)}