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")
        // 过滤出集合中的int
        numbers.filterIsInstance<Int>().forEach {
            // 打印结果是1
            Log.d("=======int元素", it.toString())
        }
        // 过滤出集合中的String
        numbers.filterIsInstance<String>().forEach {
            // 打印结果是two, four
            Log.d("=======String元素", it)
        }
相关推荐
奕鼎竜瑆3 小时前
Solid 前端响应式开发从零到精通
前端·人工智能
动恰客流统计4 小时前
景区客流统计怎么做?兼顾管控与运营的实施方案解析
大数据·前端·人工智能
派小心.4 小时前
A/B测试工具免费版够用吗?
前端·数据分析
m0_380743874 小时前
C++中的freopen的用法实例详解
开发语言·c++
前端snow5 小时前
ai agent --- redis 缓存
前端
Escalating_xu5 小时前
【Python】基础语法(1):常量、变量、类型、输入输出与运算符
开发语言·python
jimy15 小时前
polymorph.cpp里面的“析构函数、智能指针”问题
开发语言·c++
m0_380743875 小时前
PHP 8.3 缓存清除不生效怎么排查
开发语言·php
duanshu_6 小时前
官网表单与下载异常怎么排查?五个环节定位故障
前端·自动化·flyweight
朝朝辞暮i6 小时前
C++ 第 6 课:switch —— 多状态选择
开发语言·c++·算法