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)
        }
相关推荐
excel1 天前
ES6 中函数的双重调用方式:fn() 与 fn\...``
前端
可乐爱宅着1 天前
全栈框架next.js入手指南
前端·next.js
你的人类朋友1 天前
什么是API签名?
前端·后端·安全
会豪1 天前
Electron-Vite (一)快速构建桌面应用
前端
中微子1 天前
React 执行阶段与渲染机制详解(基于 React 18+ 官方文档)
前端
唐某人丶1 天前
教你如何用 JS 实现 Agent 系统(2)—— 开发 ReAct 版本的“深度搜索”
前端·人工智能·aigc
中微子1 天前
深入剖析 useState产生的 setState的完整执行流程
前端
遂心_1 天前
JavaScript 函数参数传递机制:一道经典面试题解析
前端·javascript
小徐_23331 天前
uni-app vue3 也能使用 Echarts?Wot Starter 是这样做的!
前端·uni-app·echarts
RoyLin1 天前
TypeScript设计模式:适配器模式
前端·后端·node.js