Kotlin 迭代器模式适用于以下几种情况:
val list = listOf("apple", "banana", "cherry")
for (item in list.iterator()) {
println(item)
}
reversed()
函数以相反的顺序遍历列表。val list = listOf("apple", "banana", "cherry")
for (item in list.reversed()) {
println(item)
}
class LazyList<T> {
private val items = mutableListOf<T>()
private var iterator: Iterator<T>? = null
fun add(item: T) {
items.add(item)
iterator = null
}
fun iterator(): Iterator<T> {
if (iterator == null) {
iterator = items.iterator()
}
return iterator!!
}
}
val lazyList = LazyList<Int>()
lazyList.add(1)
lazyList.add(2)
lazyList.add(3)
for (item in lazyList) {
println(item * 2)
}
filter
操作,返回一个新的列表,其中包含满足特定条件的元素。fun <T> List<T>.filter(predicate: (T) -> Boolean): List<T> {
val filteredList = mutableListOf<T>()
for (item in this) {
if (!predicate(item)) {
filteredList.add(item)
}
}
return filteredList
}
val list = listOf(1, 2, 3, 4, 5)
val evenNumbers = list.filter { it % 2 == 0 }
println(evenNumbers) // 输出: [2, 4]
总之,Kotlin 迭代器模式在需要遍历集合、支持多种遍历顺序、延迟计算以及抽象化集合操作等场景下非常有用。