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)

}

推荐文章

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。