kotlin 集合转换:map、mapindexed、mapnotnull、mapkeys、mapvalues、flatten、flatmap
引言
在之前的主题中,我们学习了如何筛选(filter)和排序(sort)集合。然而,处理集合时最重要的任务之一是转换集合中的元素。本主题将教你如何使用 kotlin 的转换函数将一个集合转换为另一个集合。
映射(mapping)
map()
用于将集合中的每个元素应用一个转换函数,返回一个新集合。
一对一转换:每个原始元素都对应一个转换后的元素。
示例:
val numbers = listof(1, 2, 3) println(numbers.map { it * 2 }) // [2, 4, 6]
mapindexed()
- 和
map()
类似,但提供元素的 索引 作为额外参数。
val words = listof("anne", "michael", "caroline") println(words.mapindexed { index, value -> if (index % 2 == 0) value.uppercase() else value }) // [anne, michael, caroline]
应用场景
获取每个字符串长度:
words.map { it.length }
将字符串转为整数:
listof("1", "2", "3").map { it.toint() }
首字母大写:
words.map { it.capitalize() }
转换 map 的键或值
可空类型的映射(mapping with nullables)
如果某些元素无法转换,map()
会返回 null
,集合变成 list<t?>
。为避免 null
,使用:
mapnotnull()
/ mapindexednotnull()
- 自动过滤掉为 null 的结果,使结果为非空集合(
list<t>
)。
val numbers = listof(1, 2, 3, 4, 5) println(numbers.map { if (it % 2 == 0) it else null }) // [null, 2, null, 4, null] println(numbers.mapnotnull { if (it % 2 == 0) it else null }) // [2, 4]
映射 map 类型(map mapping)
kotlin 的 map
类型可以使用以下两种方法转换:
mapkeys()
- 转换 map 的 键
mapvalues()
- 转换 map 的 值
val map = mapof(1 to "one", 2 to "two") println(map.mapkeys { it.key * 2 }) // {2=one, 4=two} println(map.mapvalues { it.value.uppercase() }) // {1=one, 2=two}
flatten(扁平化)
flatten()
- 把嵌套集合(list of lists)展开成一个单一列表。
val nested = listof(listof(1,2), listof(3,4)) println(nested.flatten()) // [1, 2, 3, 4]
flatmap()
- 先
map
,再flatten
,适用于一对多转换。
val nested = listof(listof(1,2), listof(3,4)) println(nested.flatmap { it.map { it * 2 } }) // [2, 4, 6, 8]
- 也可以用于 list<map> :
val listofmaps = listof(mapof(1 to "one"), mapof(2 to "two")) val result = listofmaps.flatmap { it.entries }.associate { it.topair() } println(result) // {1=one, 2=two}
总结(conclusion)
我们学到了多种转换集合的方式:
功能 | 方法 |
---|---|
一对一转换 | map() |
一对一+索引 | mapindexed() |
过滤 null 结果 | mapnotnull() |
map 键值转换 | mapkeys() / mapvalues() |
多对一 | flatten() |
一对多 | flatmap() |
到此这篇关于kotlin map映射转换的文章就介绍到这了,更多相关kotlin map映射内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!