面试题答案
一键面试map操作符
- 作用:
map
操作符用于将流中的每个元素按照指定的变换函数进行转换,生成一个新的流,新流中的元素是原流元素经过变换后的结果。 - 示例:
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
fun main() = runBlocking<Unit> {
val numbersFlow: Flow<Int> = flow {
emit(1)
emit(2)
emit(3)
}
val squaredFlow: Flow<Int> = numbersFlow.map { it * it }
squaredFlow.collect { println(it) }
}
在上述示例中,numbersFlow
流中的每个元素经过map
操作符中的变换函数{ it * it }
,将原流中的数字转换为其平方,squaredFlow
流输出的就是这些平方数。
filter操作符
- 作用:
filter
操作符用于从流中过滤出满足指定条件的元素,生成一个新的流,新流只包含满足条件的元素。 - 示例:
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.filter
fun main() = runBlocking<Unit> {
val numbersFlow: Flow<Int> = flow {
emit(1)
emit(2)
emit(3)
emit(4)
}
val evenNumbersFlow: Flow<Int> = numbersFlow.filter { it % 2 == 0 }
evenNumbersFlow.collect { println(it) }
}
在这个例子中,numbersFlow
流中的元素经过filter
操作符,通过条件it % 2 == 0
过滤出偶数,evenNumbersFlow
流只包含这些偶数。