Kotlin 迭代器模式適用于以下幾種情況:
val list = listOf("apple", "banana", "cherry")
for (item in list.iterator()) {
println(item)
}
reversed()
函數(shù)以相反的順序遍歷列表。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 迭代器模式在需要遍歷集合、支持多種遍歷順序、延遲計算以及抽象化集合操作等場景下非常有用。