KOTLIN的map集合操作

private val favoriteCollectionsData = listOf(

R.drawable.fc1_short_mantras to R.string.fc1_short_mantras,

R.drawable.fc2_nature_meditations to R.string.fc2_nature_meditations,

R.drawable.fc3_stress_and_anxiety to R.string.fc3_stress_and_anxiety,

R.drawable.fc4_self_massage to R.string.fc4_self_massage,

R.drawable.fc5_overwhelmed to R.string.fc5_overwhelmed,

R.drawable.fc6_nightly_wind_down to R.string.fc6_nightly_wind_down

).map { DrawableStringPair(it.first, it.second) }

private data class DrawableStringPair(

@DrawableRes val drawable: Int,

@StringRes val text: Int

)

  • listOf 是 Kotlin 标准库中的一个函数,用于创建一个不可变的列表。
  • R.drawableR.string 是 Android 项目中自动生成的资源类。R.drawable 包含所有的图像资源,R.string 包含所有的字符串资源。
  • to 是 Kotlin 中的中缀函数,用于创建 Pair 对象。例如,R.drawable.ab1_inversions to R.string.ab1_inversions 会创建一个 Pair<Int, Int> 对象,其中第一个元素是 R.drawable.ab1_inversions 的资源 ID,第二个元素是 R.string.ab1_inversions 的资源 ID。

因此,这部分代码创建了一个包含 6 个 Pair<Int, Int> 对象的列表,每个 Pair 对象都将一个图像资源 ID 与一个字符串资源 ID 关联起来。

  • map 是 Kotlin 集合类的扩展函数,用于对列表中的每个元素应用一个转换函数,并返回一个包含转换结果的新列表。
  • it 是 Kotlin 中的隐式参数名,在 Lambda 表达式中,如果 Lambda 只有一个参数,可以省略参数声明,直接使用 it 来引用该参数。在这里,it 代表列表中的每个 Pair<Int, Int> 对象。
  • it.firstit.second 分别是 Pair 对象的第一个和第二个元素,即图像资源 ID 和字符串资源 ID。
  • DrawableStringPair 是一个自定义类,用于存储图像资源 ID 和字符串资源 ID 的组合。代码通过 DrawableStringPair(it.first, it.second) 创建一个新的 DrawableStringPair 对象,并将其添加到新列表中。

fun main() { // 定义一个整数列表 val numbers = listOf(1, 2, 3, 4, 5) // 使用 map 函数对列表中的每个元素进行平方运算 val squaredNumbers = numbers.map { it * it } // 输出结果 println(squaredNumbers) }

fun main() { // 定义一个字符串列表 val words = listOf("hello", "world", "kotlin") // 使用 map 函数将列表中的每个字符串转换为大写 val upperCaseWords = words.map { it.uppercase() } // 输出结果 println(upperCaseWords) }

// 定义一个自定义类 data class Person(val name: String, val age: Int) fun main() { // 创建 Person 对象的列表 val people = listOf( Person("Alice", 25), Person("Bob", 30), Person("Charlie", 35) ) // 使用 map 函数提取每个人的名字 val names = people.map { it.name } // 输出结果 println(names) }

Kotlin 提供了丰富的集合操作函数,这些函数可以方便地对集合进行过滤、映射、排序、聚合等操作

相关推荐
Kapaseker1 天前
一杯美式搞定 Kotlin 空安全
android·kotlin
FunnySaltyFish2 天前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack
Kapaseker2 天前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
Kapaseker3 天前
实战 Compose 中的 IntrinsicSize
android·kotlin
A0微声z5 天前
Kotlin Multiplatform (KMP) 中使用 Protobuf
kotlin
alexhilton5 天前
使用FunctionGemma进行设备端函数调用
android·kotlin·android jetpack
lhDream6 天前
Kotlin 开发者必看!JetBrains 开源 LLM 框架 Koog 快速上手指南(含示例)
kotlin
RdoZam6 天前
Android-封装基类Activity\Fragment,从0到1记录
android·kotlin
Kapaseker6 天前
研究表明,开发者对Kotlin集合的了解不到 20%
android·kotlin
郑州光合科技余经理6 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php