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

2024-01-02 14:41:06

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

文章来源:https://blog.csdn.net/qq_33210042/article/details/135338634
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。