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)}