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

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

相关推荐
sky北城22 分钟前
You are not able to choose some of the languages, because locales for them a
android
儿歌八万首28 分钟前
Jetpack Compose 实战:打造高性能轮播图 (Carousel) 组件
android·前端·kotlin
QING61832 分钟前
Kotlin Flow 防抖(Debounce)详解
android·kotlin·android jetpack
QING61844 分钟前
Kotlin Flow 防抖(Debounce)、节流(Throttle)、去重(distinctUntilChanged) —— 新手指南
android·kotlin·android jetpack
AI视觉网奇1 小时前
android yolo12 android 实战笔记
android·笔记·yolo
海上飞猪1 小时前
【Mysql】Mysql的安装部署和使用
android·mysql·adb
我是好小孩2 小时前
【Android】项目的组件化搭建
android
aqi002 小时前
FFmpeg开发笔记(九十四)基于Kotlin的国产开源推拉流框架anyRTC
android·ffmpeg·kotlin·音视频·直播·流媒体
马 孔 多 在下雨2 小时前
Android 组件化开发基础实践
android
技术摆渡人2 小时前
Android 系统技术探索(2)构建大脑(System Services & PMS)
android