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 { ... }

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

相关推荐
doublelixin23 分钟前
AOSP (Android11) 集成Google GMS三件套
android
xzkyd outpaper3 小时前
onSaveInstanceState() 和 ViewModel 在数据保存能力差异
android·计算机八股
梓仁沐白4 小时前
【Kotlin】协程
开发语言·python·kotlin
CYRUS STUDIO4 小时前
FART 脱壳某大厂 App + CodeItem 修复 dex + 反编译还原源码
android·安全·逆向·app加固·fart·脱壳
WAsbry5 小时前
现代 Android 开发自定义主题实战指南
android·kotlin·material design
xzkyd outpaper5 小时前
Android动态广播注册收发原理
android·计算机八股
唐墨1235 小时前
android与Qt类比
android·开发语言·qt
林林要一直努力6 小时前
Android Studio 向模拟器手机添加照片、视频、音乐
android·智能手机·android studio
AD钙奶-lalala6 小时前
Mac版本Android Studio配置LeetCode插件
android·ide·android studio
梓仁沐白7 小时前
【Kotlin】注解&反射&扩展
开发语言·python·kotlin