Kotlin 集合过滤全指南:all、any、filter 及高级用法

在 Kotlin 中,集合过滤是数据处理的核心操作之一。无论是简单的条件筛选,还是复杂的多条件组合,Kotlin 都提供了丰富的 API。本文将详细介绍 filterallanynone 等操作符的用法,并展示如何在实际开发中灵活运用它们。


1. 基础过滤:filter

filter 是最常用的集合过滤方法,用于筛选满足条件的元素。

基本用法

kotlin 复制代码
val numbers = listOf(1, 2, 3, 4, 5, 6)

// 过滤偶数
val evenNumbers = numbers.filter { it % 2 == 0 }
println(evenNumbers) // [2, 4, 6]

结合 map 进行转换

kotlin 复制代码
val names = listOf("Alice", "Bob", "Charlie")

// 过滤长度 > 3 并转为大写
val result = names.filter { it.length > 3 }.map { it.uppercase() }
println(result) // ["ALICE", "CHARLIE"]

2. 多条件过滤

AND 逻辑(全部符合)

使用 &&all 实现多条件同时满足:

kotlin 复制代码
data class Product(val name: String, val price: Double, val inStock: Boolean)

val products = listOf(
    Product("iPhone", 999.0, true),
    Product("Shoes", 59.99, false),
    Product("Laptop", 1200.0, true)
)

// 过滤价格 < 1000 且库存充足的商品
val affordableAndInStock = products.filter { it.price < 1000 && it.inStock }
println(affordableAndInStock) // [Product(name=iPhone, price=999.0, inStock=true)]

OR 逻辑(符合其中一个)

使用 ||any 实现至少满足一个条件:

kotlin 复制代码
// 过滤价格 < 100 或库存为 false 的商品
val cheapOrOutOfStock = products.filter { it.price < 100 || !it.inStock }
println(cheapOrOutOfStock) // [Product(name=Shoes, price=59.99, inStock=false)]

3. 高级过滤操作

all:检查所有元素是否满足条件

kotlin 复制代码
val numbers = listOf(10, 20, 30)

// 是否所有数字 > 5?
val allGreaterThan5 = numbers.all { it > 5 }
println(allGreaterThan5) // true

any:检查是否有任意元素满足条件

kotlin 复制代码
// 是否有数字 > 25?
val anyGreaterThan25 = numbers.any { it > 25 }
println(anyGreaterThan25) // true

none:检查是否没有元素满足条件

kotlin 复制代码
// 是否没有数字 > 50?
val noneGreaterThan50 = numbers.none { it > 50 }
println(noneGreaterThan50) // true

4. 复杂场景:动态条件过滤

如果需要根据运行时条件动态过滤,可以使用高阶函数:

kotlin 复制代码
data class Person(val name: String, val age: Int, val city: String)

val people = listOf(
    Person("Alice", 25, "New York"),
    Person("Bob", 30, "London"),
    Person("Charlie", 20, "Paris")
)

// 动态条件列表
val conditions = listOf<Person.() -> Boolean>(
    { age >= 20 },
    { city == "London" || city == "Paris" }
)

// 过滤满足所有条件的人
val filteredPeople = people.filter { person ->
    conditions.all { condition -> condition(person) }
}
println(filteredPeople) // [Bob, Charlie]

5. 性能优化

使用 asSequence 进行惰性计算

kotlin 复制代码
val bigList = (1..1_000_000).toList()

// 惰性过滤,提高性能
val result = bigList.asSequence()
    .filter { it % 2 == 0 }
    .take(10)
    .toList()
println(result) // [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

预编译正则表达式(适用于 Regex 过滤)

kotlin 复制代码
val regexList = listOf(Regex("^A.*"), Regex(".*e$"))

val names = listOf("Alice", "Bob", "Eve", "Anna")

// 匹配任意一个正则
val matchedNames = names.filter { name ->
    regexList.any { it.matches(name) }
}
println(matchedNames) // ["Alice", "Anna"]

6. 实际应用:RecyclerView 搜索过滤

在 Android 开发中,filter 常用于 RecyclerView 的搜索功能:

kotlin 复制代码
class UserAdapter(private var users: List<User>) : RecyclerView.Adapter<UserAdapter.ViewHolder>() {

    fun filter(query: String) {
        users = users.filter { it.name.contains(query, ignoreCase = true) }
        notifyDataSetChanged()
    }

    // ... 其他 Adapter 代码
}

总结

需求 方法 示例
简单过滤 filter list.filter { it > 5 }
多条件 AND &&all filter { it.price > 100 && it.inStock }
多条件 OR `
反向过滤 none list.none { it.isEmpty() }
动态条件 高阶函数 conditions.all { it(item) }
性能优化 asSequence bigList.asSequence().filter { ... }

通过灵活组合这些操作符,你可以轻松应对各种集合过滤需求!

相关推荐
时光少年2 小时前
Android 副屏录制方案
android·前端
时光少年2 小时前
Android 局域网NIO案例实践
android·前端
alexhilton3 小时前
Jetpack Compose的性能优化建议
android·kotlin·android jetpack
流浪汉kylin3 小时前
Android TextView SpannableString 如何插入自定义View
android
火柴就是我4 小时前
git rebase -i,执行 squash 操作 进行提交合并
android
你说你说你来说5 小时前
安卓广播接收器(Broadcast Receiver)的介绍与使用
android·笔记
你说你说你来说5 小时前
安卓Content Provider介绍及使用
android·笔记
天枢破军5 小时前
【KMP】桌面端打包指南
kotlin
RichardLai885 小时前
[Flutter学习之Dart基础] - 类
android·flutter
_一条咸鱼_6 小时前
深度解析 Android MVI 架构原理
android·面试·kotlin