跳转到正文
YGJoon 技术博客

Android Kotlin 集合操作与标准库实战

发布于:
·913 字 · 约 2 分钟·作者:
Kotlin 集合与标准库的高效用法:map/filter 变换、Sequence 惰性求值,列表差分更新与配置合并两个业务案例。
Android Kotlin 集合操作与标准库实战文章封面
目录

Kotlin 集合体系

接口功能可变性
List<T>有序集合,允许重复不可变
MutableList<T>可变列表可变
Set<T>无重复元素集合不可变
Map<K, V>键值对映射不可变
val immutableList = listOf("A", "B")
val mutableList = mutableListOf("A", "B").apply { add("C") }

常用扩展函数

1. 变换类

val titles = articles.mapNotNull { it.title?.takeIf(String::isNotBlank) }

2. 过滤类

val systemNotifications = notifications.filterIsInstance<Notification.System>()

3. 汇总类

val totalUnread = dialogs.fold(0) { acc, dialog -> acc + dialog.unreadCount }

val dialogMap = dialogs.associateBy { it.id }

4. 排序与去重

val sorted = messages.sortedWith(compareByDescending<Message> { it.pinned }.thenByDescending { it.timestamp })

序列(Sequence)

val result = generateSequence(1) { it + 1 }
    .map { it * 2 }
    .take(5)
    .toList() // [2,4,6,8,10]

Android 业务案例

1. 列表差分更新

fun calculateDiff(old: List<User>, new: List<User>): DiffUtil.DiffResult {
    val callback = object : DiffUtil.Callback() {
        override fun getOldListSize() = old.size
        override fun getNewListSize() = new.size
        override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) =
            old[oldItemPosition].id == new[newItemPosition].id
        override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) =
            old[oldItemPosition] == new[newItemPosition]
    }
    return DiffUtil.calculateDiff(callback)
}

结合 map、groupBy 可在数据刷新前进行预处理。

2. 多模块配置合并

val config = buildList {
    addAll(commonConfig)
    if (BuildConfig.DEBUG) add(debugConfig)
    addAll(remoteConfig)
}

val configMap = config.associateBy({ it.key }, { it.value })

3. Flow 数据映射

val uiState = repository.observeArticles()
    .map { list ->
        list.groupBy { it.category }
            .mapValues { (_, items) -> items.sortedByDescending { it.publishTime } }
    }

性能优化建议

调试技巧

val result = items
    .onEach { Timber.d("step1=$it") }
    .filter { it.isValid }
    .onEach { Timber.d("step2=$it") }
    .map { it.toUiModel() }

实战案例:集合 API 是 Kotlin 最”爽”的部分

Kotlin 的集合操作(map/filter/groupBy/associateBy)和 Dart 的 Iterable 方法几乎一一对应,但 Kotlin 多了两个杀器:

  1. associateBy:users.associateBy { it.id } 一行得到 Map<String, User>。Dart 里要写 Map.fromEntries(users.map((u) => MapEntry(u.id, u))),啰嗦三倍。我在手写 JSON 工具(ygking_json_to_dart_model)里,大量用 Dart 的 map.forEach((key, value) => ...) 遍历,Kotlin 侧直接 map.forEach { (k, v) -> } 解构,更干净。
  2. Sequence 惰性求值:list.asSequence().filter { }.map { }.toList(),中间不产生临时集合。Dart 的 Iterable 默认就是惰性的(map 返回 lazy Iterable),Kotlin 反而要显式 asSequence()——两边默认值相反,切换语言时注意。

还有个冷知识:Kotlin 的 listOf 返回的是只读视图(List),mutableListOf 才是可变的。Dart 的 List 默认可变,List.unmodifiable 才只读。这个默认值差异,是 Java 系”防御性拷贝”文化的遗产,初学者经常在”为什么 add 报错”上卡半天。

一句话:Kotlin 集合库是”把 Guava 内置进了语言”,Dart 是”标准库够用但得自己拼”。各有千秋。

参考:Kotlin 官方文档《Collections overview》

总结

  1. Kotlin 集合框架通过丰富的扩展函数简化数据处理流程。
  2. 合理利用序列与不可变集合,可提升性能并减少副作用。
  3. 在 Android 场景中,将集合操作与 DiffUtil、Flow 等框架结合,能实现简洁高效的数据流处理。

下一篇将介绍协程基础与调度器,为异步任务打下扎实基础。


分享这篇文章:


相关文章

上一篇
Android Kotlin 面向对象与委托模式
下一篇
Android Kotlin 协程基础与调度器