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)
        }
相关推荐
秋田君4 分钟前
Qt_QVariant
开发语言·qt
江华森7 分钟前
Python 实现高德地图找房(三):地图可视化与高德 JS API
开发语言·javascript·python
谭光志9 分钟前
AI 是怎么操作浏览器的——browser use 实现原理
前端·javascript·ai编程
weixin_4713830312 分钟前
args,...args与Parameters<T>
开发语言·前端
ctrl_v助手1 小时前
C#表达题笔记
开发语言·c#
一tiao咸鱼1 小时前
前端转 agent # 03 - Pydantic v2 数据校验深入
前端·后端
Cobyte1 小时前
23.Vue Vapor 组件 attrs 的实现
前端·javascript·vue.js
前端H2 小时前
生成式 UI 实战:AI 如何重塑前端界面
前端·人工智能·ui
懂懂tty2 小时前
Web前端性能指标
前端
2zcode2 小时前
基于MATLAB卷积神经网络的口罩佩戴检测系统
开发语言·matlab·cnn