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

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

相关推荐
2501_915909061 小时前
iOS 应用反调试技详解术 检测调试器的原理与防护实践
android·ios·小程序·https·uni-app·iphone·webview
Lvan的前端笔记2 小时前
AndroidX 完全入门指南
android·androidx
帅次2 小时前
Android 应用高级面试:Window 近1年高频追问 18 题
android·面试·职场和发展
总捣什么乱13 小时前
MySQL MySQL是怎么保证主备一致的?
android·mysql·adb
zzm6283 小时前
精读 HinDroid:基于异构信息网络的安卓恶意软件检测
android
weixin_440784114 小时前
Android基础知识汇总
android·java·android studio
sbjdhjd4 小时前
安全初级 | Upload 文件上传漏洞实操
android·经验分享·安全·网络安全·开源·php·apache
small-pudding4 小时前
Cocos Creator Android 热更新方案实践:逻辑更新、远程 Bundle 与线上回滚
android
00后程序员张4 小时前
iOS加固技术路线全面解析:Bitcode模式、源码模式与汇编模式对比及爱加密优势
android·汇编·ios·小程序·uni-app·cocoa·iphone
summerkissyou19875 小时前
android - 性能 - Perfetto - 内存分析教程及例子
android·性能